summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorKim van der Riet <kpvdr@apache.org>2007-02-14 20:02:03 +0000
committerKim van der Riet <kpvdr@apache.org>2007-02-14 20:02:03 +0000
commita22f3f594d6eee7d610fb4f140e18cddd7c880f6 (patch)
tree5adb376ed217d2debaff1c0bdd59af1a1c93e829
parent9cb1922884c5b258c961046e6fd48e5152aa79d5 (diff)
downloadqpid-python-a22f3f594d6eee7d610fb4f140e18cddd7c880f6.tar.gz
First backmerge from trunk to 0-9 branch for Java. Not all java tests passing yet
git-svn-id: https://svn.apache.org/repos/asf/incubator/qpid/branches/qpid.0-9@507672 13f79535-47bb-0310-9956-ffa450edef68
-rw-r--r--gentools/src/org/apache/qpid/gentools/DotnetGenerator.java339
-rw-r--r--gentools/src/org/apache/qpid/gentools/JavaGenerator.java135
-rw-r--r--gentools/src/org/apache/qpid/gentools/Main.java53
-rw-r--r--gentools/templ.java/MethodBodyClass.tmpl116
-rw-r--r--gentools/templ.java/MethodRegistryClass.tmpl115
-rw-r--r--java/broker/bin/qpid-server-bdb.bat3
-rw-r--r--java/broker/bin/qpid-server.bat6
-rw-r--r--java/broker/distribution/pom.xml153
-rw-r--r--java/broker/distribution/src/main/assembly/broker-bin-tests.xml116
-rw-r--r--java/broker/distribution/src/main/assembly/broker-bin.xml171
-rw-r--r--java/broker/distribution/src/main/assembly/broker-src.xml78
-rw-r--r--java/broker/etc/config.xml35
-rw-r--r--java/broker/etc/log4j.xml21
-rw-r--r--java/broker/etc/virtualhosts.xml12
-rw-r--r--java/broker/pom.xml56
-rw-r--r--java/broker/src/main/grammar/SelectorParser.jj9
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/AMQBrokerManagerMBean.java54
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/AMQChannel.java831
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/Main.java27
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/RequiredDeliveryException.java47
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/ack/TxAck.java41
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/ack/UnacknowledgedMessage.java19
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/ack/UnacknowledgedMessageMap.java57
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/ack/UnacknowledgedMessageMapImpl.java202
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/Configurator.java19
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/configuration/VirtualHostConfiguration.java24
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/AbstractExchange.java39
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/DefaultExchangeFactory.java16
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/DefaultExchangeRegistry.java11
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/DestNameExchange.java41
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/DestWildExchange.java44
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/Exchange.java16
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeFactory.java3
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeRegistry.java5
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/FanoutExchange.java39
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/HeadersBinding.java9
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/HeadersExchange.java33
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/Index.java15
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/exchange/MessageRouter.java3
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/filter/ArithmeticExpression.java9
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/filter/BooleanExpression.java13
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/filter/ComparisonExpression.java15
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/filter/ConstantExpression.java118
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/filter/Expression.java9
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/filter/FilterManagerFactory.java35
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/filter/JMSSelectorFilter.java22
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/filter/LogicExpression.java12
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/filter/MessageFilter.java5
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/filter/NoConsumerFilter.java12
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/filter/PropertyExpression.java190
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/filter/SimpleFilterManager.java11
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/filter/UnaryExpression.java15
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/filter/XPathExpression.java21
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/filter/XQueryExpression.java9
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/filter/XalanXPathEvaluator.java32
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/ChannelCloseHandler.java19
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/ChannelCloseOkHandler.java13
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/ChannelFlowHandler.java36
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/ChannelOpenHandler.java24
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionCloseMethodHandler.java22
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionCloseOkMethodHandler.java14
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionOpenMethodHandler.java57
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionSecureOkMethodHandler.java40
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionStartOkMethodHandler.java39
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionTuneOkMethodHandler.java19
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeBoundHandler.java90
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeDeclareHandler.java39
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeDeleteHandler.java28
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/MessageAppendHandler.java20
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/MessageCancelHandler.java24
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/MessageCheckpointHandler.java11
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/MessageCloseHandler.java22
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/MessageConsumeHandler.java36
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/MessageEmptyHandler.java13
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/MessageGetHandler.java96
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/MessageOffsetHandler.java11
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/MessageOkHandler.java11
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/MessageOpenHandler.java22
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/MessageQosHandler.java20
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/MessageRecoverHandler.java30
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/MessageRejectHandler.java13
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/MessageResumeHandler.java11
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/MessageTransferHandler.java59
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/QueueBindHandler.java29
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/QueueDeclareHandler.java58
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/QueueDeleteHandler.java40
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/QueuePurgeHandler.java62
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/TxCommitHandler.java35
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/TxRollbackHandler.java30
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/handler/TxSelectHandler.java19
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/management/DefaultManagedObject.java44
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/management/ManagedBroker.java2
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/message/jms/JMSMessage.java301
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/protocol/AMQMinaProtocolSession.java210
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/protocol/AMQPFastProtocolHandler.java42
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/protocol/AMQPProtocolProvider.java3
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolSession.java34
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolSessionMBean.java20
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/protocol/ExchangeInitialiser.java3
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/AMQMessage.java452
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/AMQMessageHandle.java74
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueue.java252
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueueMBean.java143
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/AMQReference.java97
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/ConcurrentDeliveryManager.java363
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/ConcurrentSelectorDeliveryManager.java121
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/DefaultQueueRegistry.java18
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/DeliveryManager.java19
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/ExchangeBindings.java9
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/InMemoryMessageHandle.java127
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/ManagedQueue.java11
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/MessageCleanupException.java4
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/MessageHandleFactory.java46
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/MessageMetaData.java56
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/NoConsumersException.java3
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/QueueRegistry.java8
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/Subscription.java12
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/SubscriptionFactory.java5
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/SubscriptionImpl.java150
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/SubscriptionSet.java4
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/SynchronizedDeliveryManager.java265
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/TransientMessageData.java102
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/queue/WeakReferenceMessageHandle.java197
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/registry/ApplicationRegistry.java32
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/registry/ConfigurationFileApplicationRegistry.java66
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/registry/IApplicationRegistry.java18
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/auth/AuthenticationManager.java2
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/auth/NullAuthenticationManager.java1
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/auth/SASLAuthenticationManager.java1
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/security/auth/amqplain/AmqPlainSaslServer.java4
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/state/AMQStateManager.java80
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/state/StateAwareMethodListener.java5
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/store/MemoryMessageStore.java117
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/store/MessageStore.java44
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/store/StoreContext.java42
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/txn/CleanupMessageOperation.java91
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/txn/DeliverMessageOperation.java74
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/txn/LocalTransactionalContext.java237
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/txn/NonTransactionalContext.java214
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/txn/StoreMessageOperation.java58
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/txn/TransactionalContext.java51
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/txn/TxnBuffer.java62
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/txn/TxnOp.java13
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/util/NullApplicationRegistry.java48
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/virtualhost/ManagedVirtualHost.java51
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHost.java211
-rw-r--r--java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHostRegistry.java52
-rw-r--r--java/broker/src/test/java/org/apache/qpid/server/exchange/HeadersBindingTest.java120
-rw-r--r--java/broker/test/lib/README1
-rw-r--r--java/broker/test/lib/junit/junit-4.0.jarbin105601 -> 0 bytes
-rw-r--r--java/broker/test/lib/junit/junit.jarbin121070 -> 0 bytes
-rw-r--r--java/client/dist/readme.txt2
-rw-r--r--java/client/distribution/pom.xml155
-rw-r--r--java/client/distribution/src/main/assembly/client-bin-tests.xml (renamed from java/distribution/src/main/assembly/client-bin.xml)93
-rw-r--r--java/client/distribution/src/main/assembly/client-bin.xml76
-rw-r--r--java/client/distribution/src/main/assembly/client-src.xml62
-rw-r--r--java/client/example/bin/set_classpath.bat50
-rwxr-xr-xjava/client/example/bin/set_classpath.sh83
-rw-r--r--java/client/pom.xml85
-rw-r--r--java/client/readme.txt31
-rw-r--r--java/client/src/main/java/client.log4j (renamed from java/systests/src/test/java/log4j.properties)56
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/AMQBrokerDetails.java13
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/AMQConnection.java88
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/AMQDestination.java253
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/AMQHeadersExchange.java10
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/AMQQueue.java50
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/AMQSession.java546
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/AMQTemporaryQueue.java4
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/AMQTopic.java22
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/AMQUndefinedDestination.java45
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/BasicMessageConsumer.java220
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/BasicMessageProducer.java222
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/CustomJMSXProperty.java (renamed from java/client/src/main/java/org/apache/qpid/client/CustomJMXProperty.java)23
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/DispatcherCallback.java36
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/MessageConsumerPair.java43
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/QpidConnectionMetaData.java2
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/failover/FailoverHandler.java7
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/failover/FailoverSupport.java2
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/handler/ChannelCloseMethodHandler.java21
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/handler/ChannelCloseOkMethodHandler.java5
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/handler/ChannelFlowOkMethodHandler.java32
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/handler/ConnectionCloseMethodHandler.java22
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/handler/ConnectionOpenOkMethodHandler.java12
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/handler/ConnectionRedirectMethodHandler.java20
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/handler/ConnectionSecureMethodHandler.java23
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/handler/ConnectionStartMethodHandler.java153
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/handler/ConnectionTuneMethodHandler.java33
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/handler/ExchangeBoundOkMethodHandler.java41
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/handler/MessageAppendMethodHandler.java25
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/handler/MessageCheckpointMethodHandler.java16
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/handler/MessageCloseMethodHandler.java18
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/handler/MessageEmptyMethodHandler.java16
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/handler/MessageOffsetMethodHandler.java18
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/handler/MessageOkMethodHandler.java16
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/handler/MessageOpenMethodHandler.java16
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/handler/MessageRejectMethodHandler.java16
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/handler/MessageResumeMethodHandler.java18
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/handler/MessageTransferMethodHandler.java19
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/handler/QueueDeleteOkMethodHandler.java43
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/AbstractBytesMessage.java6
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/AbstractBytesTypedMessage.java1
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/AbstractJMSMessage.java109
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/AbstractJMSMessageFactory.java5
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/JMSBytesMessage.java11
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/JMSBytesMessageFactory.java1
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/JMSHeaderAdapter.java (renamed from java/common/src/main/java/org/apache/qpid/framing/JMSPropertyFieldTable.java)980
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/JMSMapMessage.java11
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/JMSMapMessageFactory.java1
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/JMSObjectMessage.java12
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/JMSObjectMessageFactory.java1
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/JMSStreamMessage.java8
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/JMSStreamMessageFactory.java1
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/JMSTextMessage.java36
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/JMSTextMessageFactory.java1
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/MessageConverter.java179
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/MessageFactory.java1
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/MessageFactoryRegistry.java16
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/MessageHeaders.java188
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/message/UnprocessedMessage.java69
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/protocol/AMQProtocolHandler.java188
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/protocol/AMQProtocolSession.java95
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/protocol/BlockingMethodFrameListener.java38
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/security/amqplain/AmqPlainSaslClient.java4
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/state/AMQStateManager.java67
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/state/StateWaiter.java10
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/transport/SocketTransportConnection.java2
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/transport/TransportConnection.java2
-rw-r--r--java/client/src/main/java/org/apache/qpid/client/transport/VmPipeTransportConnection.java4
-rw-r--r--java/client/src/main/java/org/apache/qpid/jndi/PropertiesFileInitialContextFactory.java21
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/codec/BasicDeliverTest.java70
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/codec/Client.java4
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/framing/FieldTableTest.java27
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/headers/Listener.java8
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/headers/MessageFactory.java4
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/headers/Publisher.java8
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/mina/AcceptorTest.java2
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/ping/TestPingClient.java131
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/ping/TestPingProducer.java213
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/ping/TestPingPublisher.java180
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/ping/TestPingSubscriber.java132
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/requestreply1/ServiceProvidingClient.java201
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/requestreply1/ServiceRequestingClient.java303
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/requestreply1/VmRequestReply.java72
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/test/unit/client/connection/TestManyConnections.java2
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/test/unit/jndi/referenceabletest/JNDIReferenceableTest.java14
-rw-r--r--java/client/src/old_test/java/org/apache/qpid/weblogic/ServiceRequestingClient.java17
-rw-r--r--java/client/src/test/java/org/apache/qpid/client/MessageListenerMultiConsumerTest.java213
-rw-r--r--java/client/src/test/java/org/apache/qpid/client/MessageListenerTest.java164
-rw-r--r--java/client/src/test/java/org/apache/qpid/client/message/TestNonQpidTextMessage.java231
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/ack/RecoverTest.java106
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/basic/BytesMessageTest.java2
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/basic/FieldTableKeyEnumeratorTest.java16
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/basic/FieldTableMessageTest.java19
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/basic/MapMessageTest.java24
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/basic/MultipleConnectionTest.java4
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/basic/ObjectMessageTest.java2
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/basic/PropertyValueTest.java11
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/basic/PubSubTwoConnectionRefTest.java81
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/basic/PubSubTwoConnectionTest.java4
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/basic/ReceiveTest.java2
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/basic/SelectorTest.java2
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/basic/SessionStartTest.java2
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/basic/TextMessageTest.java4
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/client/AMQConnectionTest.java12
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/client/AMQSessionTest.java2
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/client/channelclose/ChannelCloseOkTest.java23
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/client/channelclose/CloseWithBlockingReceiveTest.java2
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/client/connection/ConnectionTest.java11
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/client/connectionurl/ConnectionURLTest.java105
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/client/forwardall/Client.java24
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/client/forwardall/Service.java2
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/client/forwardall/SpecialQueue.java9
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/client/message/ObjectMessageTest.java9
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/client/protocol/AMQProtocolSessionTest.java13
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/client/temporaryqueue/TemporaryQueueTest.java2
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/close/TopicPublisherCloseTest.java2
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/message/JMSDestinationTest.java7
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/message/JMSPropertiesTest.java100
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/message/MessageConverterTest.java109
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/message/StreamMessageTest.java36
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/topic/DurableSubscriptionTest.java21
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/topic/TopicPublisherTest.java2
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/topic/TopicSessionTest.java23
-rw-r--r--java/client/src/test/java/org/apache/qpid/test/unit/transacted/TransactedTest.java37
-rw-r--r--java/cluster/src/main/java/org/apache/qpid/server/cluster/ClientHandlerRegistry.java5
-rw-r--r--java/cluster/src/main/java/org/apache/qpid/server/cluster/ClusterBuilder.java4
-rw-r--r--java/cluster/src/main/java/org/apache/qpid/server/cluster/ClusterCapability.java16
-rw-r--r--java/cluster/src/main/java/org/apache/qpid/server/cluster/ClusteredProtocolHandler.java18
-rw-r--r--java/cluster/src/main/java/org/apache/qpid/server/cluster/ClusteredProtocolSession.java28
-rw-r--r--java/cluster/src/main/java/org/apache/qpid/server/cluster/DefaultGroupManager.java73
-rw-r--r--java/cluster/src/main/java/org/apache/qpid/server/cluster/Main.java2
-rw-r--r--java/cluster/src/main/java/org/apache/qpid/server/cluster/MemberHandle.java4
-rw-r--r--java/cluster/src/main/java/org/apache/qpid/server/cluster/MinaBrokerProxy.java9
-rw-r--r--java/cluster/src/main/java/org/apache/qpid/server/cluster/ServerHandlerRegistry.java17
-rw-r--r--java/cluster/src/main/java/org/apache/qpid/server/cluster/SimpleBodySendable.java45
-rw-r--r--java/cluster/src/main/java/org/apache/qpid/server/cluster/SimpleMemberHandle.java13
-rw-r--r--java/cluster/src/main/java/org/apache/qpid/server/cluster/SimpleSendable.java28
-rw-r--r--java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/ChainedClusterMethodHandler.java9
-rw-r--r--java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/ChannelQueueManager.java26
-rw-r--r--java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/ClusterMethodHandler.java12
-rw-r--r--java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/ClusterMethodHandlerFactory.java33
-rw-r--r--java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/ExtendedHandler.java12
-rw-r--r--java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/LocalQueueDeclareHandler.java14
-rw-r--r--java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/NullListener.java2
-rw-r--r--java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/PeerHandler.java8
-rw-r--r--java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/QueueNameGenerator.java4
-rw-r--r--java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/RemoteCancelHandler.java10
-rw-r--r--java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/RemoteConsumeHandler.java9
-rw-r--r--java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/ReplicatingConsumeHandler.java14
-rw-r--r--java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/ReplicatingHandler.java39
-rw-r--r--java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/WrappedListener.java8
-rw-r--r--java/cluster/src/main/java/org/apache/qpid/server/cluster/replay/ConsumerCounts.java25
-rw-r--r--java/cluster/src/main/java/org/apache/qpid/server/cluster/replay/RecordingMethodHandlerFactory.java15
-rw-r--r--java/cluster/src/main/java/org/apache/qpid/server/cluster/replay/ReplayStore.java41
-rw-r--r--java/cluster/src/main/java/org/apache/qpid/server/queue/ClusteredQueue.java47
-rw-r--r--java/cluster/src/main/java/org/apache/qpid/server/queue/PrivateQueue.java21
-rw-r--r--java/cluster/src/main/java/org/apache/qpid/server/queue/RemoteQueueProxy.java34
-rw-r--r--java/cluster/src/main/java/org/apache/qpid/server/queue/RemoteSubscriptionImpl.java9
-rw-r--r--java/cluster/src/test/java/org/apache/qpid/server/cluster/BrokerTest.java22
-rw-r--r--java/cluster/src/test/java/org/apache/qpid/server/cluster/ClusterCapabilityTest.java5
-rw-r--r--java/cluster/src/test/java/org/apache/qpid/server/cluster/SimpleClusterTest.java3
-rw-r--r--java/common/pom.xml28
-rw-r--r--java/common/src/main/java/org/apache/qpid/AMQChannelException.java3
-rw-r--r--java/common/src/main/java/org/apache/qpid/AMQConnectionException.java5
-rw-r--r--java/common/src/main/java/org/apache/qpid/AMQConnectionFailureException.java20
-rw-r--r--java/common/src/main/java/org/apache/qpid/AMQTimeoutException.java (renamed from java/broker/src/main/java/org/apache/qpid/server/message/MessageDecorator.java)8
-rw-r--r--java/common/src/main/java/org/apache/qpid/AMQUnknownExchangeType.java20
-rw-r--r--java/common/src/main/java/org/apache/qpid/common/AMQPFilterTypes.java8
-rw-r--r--java/common/src/main/java/org/apache/qpid/exchange/ExchangeDefaults.java23
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/AMQBody.java2
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockDecoder.java89
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockEncoder.java9
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/AMQFrame.java51
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/AMQMethodBody.java5
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyFactory.java23
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyInstanceFactory.java30
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/AMQRequestBody.java30
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/AMQRequestBodyFactory.java41
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/AMQResponseBody.java27
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/AMQResponseBodyFactory.java41
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/AMQShortString.java374
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/AMQType.java6
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/AMQTypedValue.java25
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/BodyFactory.java3
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/EncodingUtils.java461
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/FieldTable.java527
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/HeartbeatBody.java16
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/HeartbeatBodyFactory.java2
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/ProtocolInitiation.java10
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/RequestManager.java4
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/ResponseManager.java11
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/SmallCompositeAMQDataBlock.java97
-rw-r--r--java/common/src/main/java/org/apache/qpid/framing/VersionSpecificRegistry.java141
-rw-r--r--java/common/src/main/java/org/apache/qpid/pool/Event.java98
-rw-r--r--java/common/src/main/java/org/apache/qpid/pool/Job.java34
-rw-r--r--java/common/src/main/java/org/apache/qpid/pool/PoolingFilter.java157
-rw-r--r--java/common/src/main/java/org/apache/qpid/pool/ReadWriteThreadModel.java39
-rw-r--r--java/common/src/main/java/org/apache/qpid/protocol/AMQConstant.java8
-rw-r--r--java/common/src/main/java/org/apache/qpid/protocol/AMQVersionAwareProtocolSession.java29
-rw-r--r--java/common/src/main/java/org/apache/qpid/protocol/ProtocolVersionAware.java30
-rw-r--r--java/common/src/main/java/org/apache/qpid/url/AMQBindingURL.java59
-rw-r--r--java/common/src/main/java/org/apache/qpid/url/BindingURL.java22
-rw-r--r--java/common/src/main/java/org/apache/qpid/util/concurrent/BooleanLatch.java42
-rw-r--r--java/common/src/test/java/org/apache/qpid/framing/JMSPropertyFieldTableTest.java1016
-rw-r--r--java/common/src/test/java/org/apache/qpid/framing/PropertyFieldTableTest.java61
-rw-r--r--java/common/src/test/java/org/apache/qpid/pool/PoolingFilterTest.java13
-rw-r--r--java/common/src/test/java/org/apache/qpid/session/TestSession.java20
-rw-r--r--java/distribution/pom.xml98
-rw-r--r--java/distribution/src/main/assembly/bin-test.xml169
-rw-r--r--java/distribution/src/main/assembly/bin.xml29
-rw-r--r--java/distribution/src/main/assembly/management-eclipse-plugin-unix.xml12
-rw-r--r--java/distribution/src/main/assembly/management-eclipse-plugin.xml7
-rw-r--r--java/distribution/src/main/assembly/src.xml6
-rwxr-xr-xjava/distribution/src/main/release/LICENSE.txt (renamed from java/LICENSE.txt)0
-rw-r--r--java/distribution/src/main/release/NOTICE.txt (renamed from java/NOTICE.txt)0
-rw-r--r--java/distribution/src/main/release/README.txt (renamed from java/README.txt)0
-rw-r--r--java/etc/log4j.xml43
-rw-r--r--java/management/eclipse-plugin/README.txt16
-rwxr-xr-xjava/management/eclipse-plugin/bin/qpidmc.sh53
-rwxr-xr-xjava/management/eclipse-plugin/bin/qpidmc_gtk.sh (renamed from java/perftests/bin/topicPublisher.sh)7
-rwxr-xr-xjava/management/eclipse-plugin/bin/qpidmc_motif.sh (renamed from java/perftests/bin/topicListener.sh)7
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/Constants.java5
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ManagedBean.java15
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ServerRegistry.java52
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/ClientListener.java2
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/ClientNotificationListener.java1
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/JMXServerRegistry.java78
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/AttributeData.java5
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/AttributesTabControl.java8
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/MBeanTypeTabControl.java13
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/MBeanView.java20
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/NavigationView.java144
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/NotificationsTabControl.java1
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/OperationTabControl.java40
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/TabControl.java27
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/TreeObject.java14
-rw-r--r--java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/ViewUtility.java62
-rw-r--r--java/management/eclipse-plugin/src/main/resources/unix/configuration/config.ini1
-rw-r--r--java/mvn-repo/README.txt5
-rw-r--r--java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/0.5-SNAPSHOT/junit-toolkit-maven-plugin-0.5-20070130.111904-1.jarbin0 -> 9768 bytes
-rw-r--r--java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/0.5-SNAPSHOT/junit-toolkit-maven-plugin-0.5-20070130.111904-1.jar.md51
-rw-r--r--java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/0.5-SNAPSHOT/junit-toolkit-maven-plugin-0.5-20070130.111904-1.jar.sha11
-rw-r--r--java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/0.5-SNAPSHOT/junit-toolkit-maven-plugin-0.5-20070130.111904-1.pom91
-rw-r--r--java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/0.5-SNAPSHOT/junit-toolkit-maven-plugin-0.5-20070130.111904-1.pom.md51
-rw-r--r--java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/0.5-SNAPSHOT/junit-toolkit-maven-plugin-0.5-20070130.111904-1.pom.sha11
-rw-r--r--java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/0.5-SNAPSHOT/maven-metadata.xml12
-rw-r--r--java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/0.5-SNAPSHOT/maven-metadata.xml.md51
-rw-r--r--java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/0.5-SNAPSHOT/maven-metadata.xml.sha11
-rw-r--r--java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/maven-metadata.xml12
-rw-r--r--java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/maven-metadata.xml.md51
-rw-r--r--java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/maven-metadata.xml.sha11
-rw-r--r--java/mvn-repo/uk/co/thebadgerset/junit-toolkit/0.5-SNAPSHOT/junit-toolkit-0.5-20070131.112634-1.jarbin0 -> 69140 bytes
-rw-r--r--java/mvn-repo/uk/co/thebadgerset/junit-toolkit/0.5-SNAPSHOT/junit-toolkit-0.5-20070131.112634-1.jar.md51
-rw-r--r--java/mvn-repo/uk/co/thebadgerset/junit-toolkit/0.5-SNAPSHOT/junit-toolkit-0.5-20070131.112634-1.jar.sha11
-rw-r--r--java/mvn-repo/uk/co/thebadgerset/junit-toolkit/0.5-SNAPSHOT/junit-toolkit-0.5-20070131.112634-1.pom111
-rw-r--r--java/mvn-repo/uk/co/thebadgerset/junit-toolkit/0.5-SNAPSHOT/junit-toolkit-0.5-20070131.112634-1.pom.md51
-rw-r--r--java/mvn-repo/uk/co/thebadgerset/junit-toolkit/0.5-SNAPSHOT/junit-toolkit-0.5-20070131.112634-1.pom.sha11
-rw-r--r--java/mvn-repo/uk/co/thebadgerset/junit-toolkit/0.5-SNAPSHOT/maven-metadata.xml12
-rw-r--r--java/mvn-repo/uk/co/thebadgerset/junit-toolkit/0.5-SNAPSHOT/maven-metadata.xml.md51
-rw-r--r--java/mvn-repo/uk/co/thebadgerset/junit-toolkit/0.5-SNAPSHOT/maven-metadata.xml.sha11
-rw-r--r--java/mvn-repo/uk/co/thebadgerset/junit-toolkit/maven-metadata.xml11
-rw-r--r--java/mvn-repo/uk/co/thebadgerset/junit-toolkit/maven-metadata.xml.md51
-rw-r--r--java/mvn-repo/uk/co/thebadgerset/junit-toolkit/maven-metadata.xml.sha11
-rw-r--r--java/mvn-repo/uk/co/thebadgerset/maven-metadata.xml9
-rw-r--r--java/mvn-repo/uk/co/thebadgerset/maven-metadata.xml.md51
-rw-r--r--java/mvn-repo/uk/co/thebadgerset/maven-metadata.xml.sha11
-rw-r--r--java/perftests/RunningPerformanceTests.txt112
-rwxr-xr-xjava/perftests/bin/run_many.sh30
-rwxr-xr-xjava/perftests/bin/serviceProvidingClient.sh25
-rwxr-xr-xjava/perftests/bin/serviceRequestingClient.sh27
-rwxr-xr-xjava/perftests/bin/setupclasspath.sh9
-rw-r--r--java/perftests/distribution/pom.xml127
-rw-r--r--java/perftests/distribution/src/main/assembly/performance.xml103
-rw-r--r--java/perftests/jar-with-dependencies.xml29
-rw-r--r--java/perftests/pom.xml203
-rw-r--r--java/perftests/src/main/java/org/apache/qpid/client/message/TestMessageFactory.java118
-rw-r--r--java/perftests/src/main/java/org/apache/qpid/ping/PingClient.java90
-rw-r--r--java/perftests/src/main/java/org/apache/qpid/requestreply/PingPongBouncer.java452
-rw-r--r--java/perftests/src/main/java/org/apache/qpid/requestreply/PingPongProducer.java1127
-rw-r--r--java/perftests/src/main/java/org/apache/qpid/requestreply/ServiceProvidingClient.java201
-rw-r--r--java/perftests/src/main/java/org/apache/qpid/requestreply/ServiceRequestingClient.java303
-rw-r--r--java/perftests/src/main/java/org/apache/qpid/topic/Config.java88
-rw-r--r--java/perftests/src/main/java/org/apache/qpid/topic/Publisher.java31
-rw-r--r--java/perftests/src/main/java/perftests.log4j45
-rw-r--r--java/perftests/src/test/java/org/apache/qpid/ping/PingAsyncTestPerf.java302
-rw-r--r--java/perftests/src/test/java/org/apache/qpid/ping/PingLatencyTestPerf.java317
-rw-r--r--java/perftests/src/test/java/org/apache/qpid/ping/PingTestPerf.java246
-rw-r--r--java/perftests/src/test/java/org/apache/qpid/requestreply/PingPongTestPerf.java259
-rw-r--r--java/pom.xml94
-rw-r--r--java/resources/DISCLAIMER5
-rwxr-xr-xjava/resources/LICENSE.txt203
-rw-r--r--java/resources/NOTICE.txt36
-rw-r--r--java/resources/README.txt40
-rw-r--r--java/systests/distribution/pom.xml111
-rw-r--r--java/systests/distribution/src/main/assembly/systests.xml91
-rw-r--r--java/systests/pom.xml53
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/AMQBrokerManagerMBeanTest.java (renamed from java/systests/src/test/java/org/apache/qpid/server/AMQBrokerManagerMBeanTest.java)38
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/ack/TxAckTest.java (renamed from java/systests/src/test/java/org/apache/qpid/server/ack/TxAckTest.java)80
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/exchange/AbstractHeadersExchangeTestBase.java330
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/exchange/ExchangeMBeanTest.java (renamed from java/systests/src/test/java/org/apache/qpid/server/exchange/ExchangeMBeanTest.java)32
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/exchange/HeadersExchangeTest.java (renamed from java/systests/src/test/java/org/apache/qpid/server/exchange/HeadersExchangeTest.java)23
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/exchange/ReturnUnroutableMandatoryMessageTest.java (renamed from java/systests/src/test/java/org/apache/qpid/server/exchange/ReturnUnroutableMandatoryMessageTest.java)3
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/protocol/AMQProtocolSessionMBeanTest.java (renamed from java/systests/src/test/java/org/apache/qpid/server/protocol/AMQProtocolSessionMBeanTest.java)55
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/protocol/MockIoSession.java (renamed from java/systests/src/test/java/org/apache/qpid/server/protocol/MockIoSession.java)0
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/queue/AMQQueueMBeanTest.java (renamed from java/systests/src/test/java/org/apache/qpid/server/queue/AMQQueueMBeanTest.java)120
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/queue/AckTest.java (renamed from java/systests/src/test/java/org/apache/qpid/server/queue/AckTest.java)185
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/queue/ConcurrencyTest.java (renamed from java/systests/src/test/java/org/apache/qpid/server/queue/ConcurrencyTest.java)18
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/queue/DeliveryManagerTest.java (renamed from java/systests/src/test/java/org/apache/qpid/server/queue/DeliveryManagerTest.java)22
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/queue/MessageTestHelper.java95
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/queue/MockProtocolSession.java (renamed from java/systests/src/test/java/org/apache/qpid/server/queue/MockProtocolSession.java)186
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/queue/SubscriptionManagerTest.java (renamed from java/systests/src/test/java/org/apache/qpid/server/queue/SubscriptionManagerTest.java)0
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/queue/SubscriptionSetTest.java (renamed from java/systests/src/test/java/org/apache/qpid/server/queue/SubscriptionSetTest.java)0
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/queue/SubscriptionTestHelper.java (renamed from java/systests/src/test/java/org/apache/qpid/server/queue/SubscriptionTestHelper.java)6
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/store/SkeletonMessageStore.java (renamed from java/systests/src/test/java/org/apache/qpid/server/store/SkeletonMessageStore.java)78
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/store/TestReferenceCounting.java135
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/store/TestableMemoryMessageStore.java (renamed from java/systests/src/test/java/org/apache/qpid/server/store/TestableMemoryMessageStore.java)21
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/txn/TxnBufferTest.java (renamed from java/systests/src/test/java/org/apache/qpid/server/txn/TxnBufferTest.java)74
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/util/AveragedRun.java (renamed from java/systests/src/test/java/org/apache/qpid/server/util/AveragedRun.java)0
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/util/RunStats.java (renamed from java/systests/src/test/java/org/apache/qpid/server/util/RunStats.java)0
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/util/TestApplicationRegistry.java (renamed from java/systests/src/test/java/org/apache/qpid/server/util/TestApplicationRegistry.java)25
-rw-r--r--java/systests/src/main/java/org/apache/qpid/server/util/TimedRun.java (renamed from java/systests/src/test/java/org/apache/qpid/server/util/TimedRun.java)0
-rw-r--r--java/systests/src/main/java/org/apache/qpid/test/VMBrokerSetup.java (renamed from java/systests/src/test/java/org/apache/qpid/test/VMBrokerSetup.java)0
-rw-r--r--java/systests/src/main/java/systests.log4j (renamed from java/client/src/main/java/log4j.properties)0
-rw-r--r--java/systests/src/old_test/java/org/apache/qpid/server/queue/SendPerfTest.java19
-rw-r--r--java/systests/src/old_test/java/org/apache/qpid/test/unit/ack/DisconnectAndRedeliverTest.java21
-rw-r--r--java/systests/src/test/java/org/apache/qpid/server/exchange/AbstractHeadersExchangeTestBase.java247
-rw-r--r--java/systests/src/test/java/org/apache/qpid/server/queue/ConcurrentDeliveryManagerTest.java50
-rw-r--r--java/systests/src/test/java/org/apache/qpid/server/queue/MessageTestHelper.java85
-rw-r--r--java/systests/src/test/java/org/apache/qpid/server/queue/SynchronizedDeliveryManagerTest.java54
-rw-r--r--java/systests/src/test/java/org/apache/qpid/server/store/TestReferenceCounting.java67
490 files changed, 19722 insertions, 10193 deletions
diff --git a/gentools/src/org/apache/qpid/gentools/DotnetGenerator.java b/gentools/src/org/apache/qpid/gentools/DotnetGenerator.java
new file mode 100644
index 0000000000..505a70dc85
--- /dev/null
+++ b/gentools/src/org/apache/qpid/gentools/DotnetGenerator.java
@@ -0,0 +1,339 @@
+/*
+ *
+ * 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.gentools;
+
+import java.io.File;
+import java.io.IOException;
+import java.lang.reflect.InvocationTargetException;
+import java.util.TreeMap;
+
+public class DotnetGenerator extends Generator
+{
+ private class DomainInfo
+ {
+ public String type;
+ public String size;
+ public String encodeExpression;
+ public String decodeExpression;
+ public DomainInfo(String domain, String size, String encodeExpression, String decodeExpression)
+ {
+ this.type = domain;
+ this.size = size;
+ this.encodeExpression = encodeExpression;
+ this.decodeExpression = decodeExpression;
+ }
+ }
+
+ private static TreeMap<String, DomainInfo> typeMap = new TreeMap<String, DomainInfo>();
+
+ public DotnetGenerator(AmqpVersionSet versionList)
+ {
+ super(versionList);
+ // Load .NET type and size maps.
+ // Adjust or add to these lists as new types are added/defined.
+ // The char '#' will be replaced by the field variable name (any type).
+ // The char '~' will be replaced by the compacted bit array size (type bit only).
+ // TODO: I have left a copy of the Java typeMap here - replace with appropriate .NET values.
+ typeMap.put("bit", new DomainInfo(
+ "boolean", // .NET code type
+ "~", // size
+ "EncodingUtils.writeBooleans(buffer, #)", // encode expression
+ "# = EncodingUtils.readBooleans(buffer)")); // decode expression
+ typeMap.put("content", new DomainInfo(
+ "Content", // .NET code type
+ "EncodingUtils.encodedContentLength(#)", // size
+ "EncodingUtils.writeContentBytes(buffer, #)", // encode expression
+ "# = EncodingUtils.readContent(buffer)")); // decode expression
+ typeMap.put("long", new DomainInfo(
+ "long", // .NET code type
+ "4", // size
+ "EncodingUtils.writeUnsignedInteger(buffer, #)", // encode expression
+ "# = buffer.getUnsignedInt()")); // decode expression
+ typeMap.put("longlong", new DomainInfo(
+ "long", // .NET code type
+ "8", // size
+ "buffer.putLong(#)", // encode expression
+ "# = buffer.getLong()")); // decode expression
+ typeMap.put("longstr", new DomainInfo(
+ "byte[]", // .NET code type
+ "EncodingUtils.encodedLongstrLength(#)", // size
+ "EncodingUtils.writeLongStringBytes(buffer, #)", // encode expression
+ "# = EncodingUtils.readLongstr(buffer)")); // decode expression
+ typeMap.put("octet", new DomainInfo(
+ "short", // .NET code type
+ "1", // size
+ "EncodingUtils.writeUnsignedByte(buffer, #)", // encode expression
+ "# = buffer.getUnsigned()")); // decode expression
+ typeMap.put("short", new DomainInfo(
+ "int", // .NET code type
+ "2", // size
+ "EncodingUtils.writeUnsignedShort(buffer, #)", // encode expression
+ "# = buffer.getUnsignedShort()")); // decode expression
+ typeMap.put("shortstr", new DomainInfo(
+ "AMQShortString", // .NET code type
+ "EncodingUtils.encodedShortStringLength(#)", // size
+ "EncodingUtils.writeShortStringBytes(buffer, #)", // encode expression
+ "# = EncodingUtils.readAMQShortString(buffer)")); // decode expression
+ typeMap.put("table", new DomainInfo(
+ "FieldTable", // .NET code type
+ "EncodingUtils.encodedFieldTableLength(#)", // size
+ "EncodingUtils.writeFieldTableBytes(buffer, #)", // encode expression
+ "# = EncodingUtils.readFieldTable(buffer)")); // decode expression
+ typeMap.put("timestamp", new DomainInfo(
+ "long", // .NET code type
+ "8", // size
+ "EncodingUtils.writeTimestamp(buffer, #)", // encode expression
+ "# = EncodingUtils.readTimestamp(buffer)")); // decode expression
+ }
+
+ @Override
+ protected String prepareFilename(String filenameTemplate,
+ AmqpClass thisClass, AmqpMethod method, AmqpField field)
+ {
+ StringBuffer sb = new StringBuffer(filenameTemplate);
+ if (thisClass != null)
+ replaceToken(sb, "${CLASS}", thisClass.name);
+ if (method != null)
+ replaceToken(sb, "${METHOD}", method.name);
+ if (field != null)
+ replaceToken(sb, "${FIELD}", field.name);
+ return sb.toString();
+ }
+
+ @Override
+ protected void processClassList(StringBuffer sb, int listMarkerStartIndex,
+ int listMarkerEndIndex, AmqpModel model)
+ throws AmqpTemplateException, AmqpTypeMappingException
+ {
+ String codeSnippet;
+ int lend = sb.indexOf(cr, listMarkerStartIndex) + 1; // Include cr at end of line
+ String tline = sb.substring(listMarkerEndIndex, lend); // Line excluding line marker, including cr
+ int tokStart = tline.indexOf('$');
+ String token = tline.substring(tokStart).trim();
+ sb.delete(listMarkerStartIndex, lend);
+
+ // TODO: Add in tokens and calls to their corresponding generator methods here...
+ if (token.compareTo("${??????????}") == 0)
+ {
+ codeSnippet = token; // This is a stub to get the compile working - remove when gen method is present.
+// codeSnippet = generateRegistry(model, 8, 4);
+ }
+
+ else // Oops!
+ {
+ throw new AmqpTemplateException("Template token " + token + " unknown.");
+ }
+ sb.insert(listMarkerStartIndex, codeSnippet);
+ }
+
+ @Override
+ protected void processConstantList(StringBuffer sb,
+ int listMarkerStartIndex, int listMarkerEndIndex,
+ AmqpConstantSet constantSet) throws AmqpTemplateException,
+ AmqpTypeMappingException
+ {
+ String codeSnippet;
+ int lend = sb.indexOf(cr, listMarkerStartIndex) + 1; // Include cr at end of line
+ String tline = sb.substring(listMarkerEndIndex, lend); // Line excluding line marker, including cr
+ int tokStart = tline.indexOf('$');
+ String token = tline.substring(tokStart).trim();
+ sb.delete(listMarkerStartIndex, lend);
+
+ // TODO: Add in tokens and calls to their corresponding generator methods here...
+ if (token.compareTo("${??????????}") == 0)
+ {
+ codeSnippet = token; // This is a stub to get the compile working - remove when gen method is present.
+// codeSnippet = generateConstantGetMethods(constantSet, 4, 4);
+ }
+
+ else // Oops!
+ {
+ throw new AmqpTemplateException("Template token " + token + " unknown.");
+ }
+ sb.insert(listMarkerStartIndex, codeSnippet);
+ }
+
+ @Override
+ protected void processFieldList(StringBuffer sb, int listMarkerStartIndex,
+ int listMarkerEndIndex, AmqpFieldMap fieldMap, AmqpVersion version)
+ throws AmqpTypeMappingException, AmqpTemplateException,
+ IllegalAccessException, InvocationTargetException
+ {
+ String codeSnippet;
+ int lend = sb.indexOf(cr, listMarkerStartIndex) + 1; // Include cr at end of line
+ String tline = sb.substring(listMarkerEndIndex, lend); // Line excluding line marker, including cr
+ int tokStart = tline.indexOf('$');
+ String token = tline.substring(tokStart).trim();
+ sb.delete(listMarkerStartIndex, lend);
+
+ // TODO: Add in tokens and calls to their corresponding generator methods here...
+ if (token.compareTo("${??????????}") == 0)
+ {
+ codeSnippet = token; // This is a stub to get the compile working - remove when gen method is present.
+// codeSnippet = fieldMap.parseFieldMap(declarationGenerateMethod,
+// mangledDeclarationGenerateMethod, 4, 4, this);
+ }
+
+ else // Oops!
+ {
+ throw new AmqpTemplateException("Template token " + token + " unknown.");
+ }
+ sb.insert(listMarkerStartIndex, codeSnippet);
+ }
+
+ @Override
+ protected void processMethodList(StringBuffer sb, int listMarkerStartIndex,
+ int listMarkerEndIndex, AmqpClass thisClass)
+ throws AmqpTemplateException, AmqpTypeMappingException
+ {
+ String codeSnippet;
+ int lend = sb.indexOf(cr, listMarkerStartIndex) + 1; // Include cr at end of line
+ String tline = sb.substring(listMarkerEndIndex, lend); // Line excluding line marker, including cr
+ int tokStart = tline.indexOf('$');
+ String token = tline.substring(tokStart).trim();
+ sb.delete(listMarkerStartIndex, lend);
+
+ // TODO: Add in tokens and calls to their corresponding generator methods here...
+ if (token.compareTo("${??????????}") == 0)
+ {
+ codeSnippet = token; // This is a stub to get the compile working - remove when gen method is present.
+ }
+
+ else // Oops!
+ {
+ throw new AmqpTemplateException("Template token " + token + " unknown.");
+ }
+ sb.insert(listMarkerStartIndex, codeSnippet);
+ }
+
+ @Override
+ protected void processTemplateA(String[] template) throws IOException,
+ AmqpTemplateException, AmqpTypeMappingException,
+ IllegalAccessException, InvocationTargetException
+ {
+ // I've put in the Java model here - this can be changed if a different pattern is required.
+ processTemplateD(template, null, null, null);
+ }
+
+ @Override
+ protected void processTemplateB(String[] template, AmqpClass thisClass)
+ throws IOException, AmqpTemplateException,
+ AmqpTypeMappingException, IllegalAccessException,
+ InvocationTargetException
+ {
+ // I've put in the Java model here - this can be changed if a different pattern is required.
+ processTemplateD(template, thisClass, null, null);
+ }
+
+ @Override
+ protected void processTemplateC(String[] template, AmqpClass thisClass,
+ AmqpMethod method) throws IOException, AmqpTemplateException,
+ AmqpTypeMappingException, IllegalAccessException,
+ InvocationTargetException
+ {
+ // I've put in the Java model here - this can be changed if a different pattern is required.
+ processTemplateD(template, thisClass, method, null);
+ }
+
+ @Override
+ protected void processTemplateD(String[] template, AmqpClass thisClass,
+ AmqpMethod method, AmqpField field) throws IOException,
+ AmqpTemplateException, AmqpTypeMappingException,
+ IllegalAccessException, InvocationTargetException
+ {
+ // I've put in the Java model here - this can be changed if a different pattern is required.
+ StringBuffer sb = new StringBuffer(template[1]);
+ String filename = prepareFilename(getTemplateFileName(sb), thisClass, method, field);
+ try { processAllLists(sb, thisClass, method, null); }
+ catch (AmqpTemplateException e)
+ {
+ System.out.println("WARNING: " + template[templateFileNameIndex] + ": " + e.getMessage());
+ }
+ try { processAllTokens(sb, thisClass, method, field, null); }
+ catch (AmqpTemplateException e)
+ {
+ System.out.println("WARNING: " + template[templateFileNameIndex] + ": " + e.getMessage());
+ }
+ writeTargetFile(sb, new File(genDir + Utils.fileSeparator + filename));
+ generatedFileCounter ++;
+ }
+
+ @Override
+ protected String processToken(String token, AmqpClass thisClass,
+ AmqpMethod method, AmqpField field, AmqpVersion version)
+ throws AmqpTemplateException, AmqpTypeMappingException
+ {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public String getDomainType(String domainName, AmqpVersion version)
+ throws AmqpTypeMappingException
+ {
+ return globalDomainMap.getDomainType(domainName, version);
+ }
+
+ public String getGeneratedType(String domainName, AmqpVersion version)
+ throws AmqpTypeMappingException
+ {
+ String domainType = globalDomainMap.getDomainType(domainName, version);
+ if (domainType == null)
+ {
+ throw new AmqpTypeMappingException("Domain type \"" + domainName +
+ "\" not found in Java typemap.");
+ }
+ DomainInfo info = typeMap.get(domainType);
+ if (info == null)
+ {
+ throw new AmqpTypeMappingException("Unknown domain: \"" + domainType + "\"");
+ }
+ return info.type;
+ }
+
+ public String prepareClassName(String className)
+ {
+ return camelCaseName(className, true);
+ }
+
+ public String prepareDomainName(String domainName)
+ {
+ return camelCaseName(domainName, false);
+ }
+
+ public String prepareMethodName(String methodName)
+ {
+ return camelCaseName(methodName, false);
+ }
+
+ private String camelCaseName(String name, boolean upperFirstFlag)
+ {
+ StringBuffer ccn = new StringBuffer();
+ String[] toks = name.split("[-_.\\ ]");
+ for (int i=0; i<toks.length; i++)
+ {
+ StringBuffer b = new StringBuffer(toks[i]);
+ if (upperFirstFlag || i>0)
+ b.setCharAt(0, Character.toUpperCase(toks[i].charAt(0)));
+ ccn.append(b);
+ }
+ return ccn.toString();
+ }
+}
diff --git a/gentools/src/org/apache/qpid/gentools/JavaGenerator.java b/gentools/src/org/apache/qpid/gentools/JavaGenerator.java
index 036af79902..9acfaf65fa 100644
--- a/gentools/src/org/apache/qpid/gentools/JavaGenerator.java
+++ b/gentools/src/org/apache/qpid/gentools/JavaGenerator.java
@@ -61,7 +61,9 @@ public class JavaGenerator extends Generator
static private Method mbGetGenerateMethod;
static private Method mbMangledGetGenerateMethod;
static private Method mbParamListGenerateMethod;
+ static private Method mbPassedParamListGenerateMethod;
static private Method mbMangledParamListGenerateMethod;
+ static private Method mbMangledPassedParamListGenerateMethod;
static private Method mbBodyInitGenerateMethod;
static private Method mbMangledBodyInitGenerateMethod;
static private Method mbSizeGenerateMethod;
@@ -131,11 +133,22 @@ public class JavaGenerator extends Generator
AmqpVersionSet.class, int.class, int.class, boolean.class); }
catch (NoSuchMethodException e) { e.printStackTrace(); }
+
+ try { mbPassedParamListGenerateMethod = JavaGenerator.class.getDeclaredMethod(
+ "generateMbPassedParamList", String.class, AmqpField.class,
+ AmqpVersionSet.class, int.class, int.class, boolean.class); }
+ catch (NoSuchMethodException e) { e.printStackTrace(); }
+
try { mbMangledParamListGenerateMethod = JavaGenerator.class.getDeclaredMethod(
"generateMbMangledParamList", AmqpField.class,
int.class, int.class, boolean.class); }
catch (NoSuchMethodException e) { e.printStackTrace(); }
+ try { mbMangledPassedParamListGenerateMethod = JavaGenerator.class.getDeclaredMethod(
+ "generateMbMangledPassedParamList", AmqpField.class,
+ int.class, int.class, boolean.class); }
+ catch (NoSuchMethodException e) { e.printStackTrace(); }
+
try { mbBodyInitGenerateMethod = JavaGenerator.class.getDeclaredMethod(
"generateMbBodyInit", String.class, AmqpField.class,
AmqpVersionSet.class, int.class, int.class, boolean.class); }
@@ -320,10 +333,10 @@ public class JavaGenerator extends Generator
"EncodingUtils.writeUnsignedShort(buffer, #)", // encode expression
"# = buffer.getUnsignedShort()")); // decode expression
typeMap.put("shortstr", new DomainInfo(
- "String", // Java code type
+ "AMQShortString", // Java code type
"EncodingUtils.encodedShortStringLength(#)", // size
"EncodingUtils.writeShortStringBytes(buffer, #)", // encode expression
- "# = EncodingUtils.readShortString(buffer)")); // decode expression
+ "# = EncodingUtils.readAMQShortString(buffer)")); // decode expression
typeMap.put("table", new DomainInfo(
"FieldTable", // Java code type
"EncodingUtils.encodedFieldTableLength(#)", // size
@@ -457,11 +470,11 @@ public class JavaGenerator extends Generator
if (token.compareTo("${CLASS}") == 0 && thisClass != null)
return thisClass.name;
if (token.compareTo("${CLASS_ID_INIT}") == 0 && thisClass != null)
- return generateIndexInitializer("classIdMap", thisClass.indexMap, 8);
+ return generateIndexInitializer("registerClassId", thisClass.indexMap, 8);
if (token.compareTo("${METHOD}") == 0 && method != null)
return method.name;
if (token.compareTo("${METHOD_ID_INIT}") == 0 && method != null)
- return generateIndexInitializer("methodIdMap", method.indexMap, 8);
+ return generateIndexInitializer("registerMethodId", method.indexMap, 8);
if (token.compareTo("${FIELD}") == 0 && field != null)
return field.name;
@@ -573,6 +586,16 @@ public class JavaGenerator extends Generator
codeSnippet += fieldMap.parseFieldMap(mbParamListGenerateMethod,
mbMangledParamListGenerateMethod, 42, 4, this);
}
+
+ else if (token.compareTo("${mb_field_passed_parameter_list}") == 0)
+ {
+ // <cringe> The code generated by this is ugly... It puts a comma on a line by itself!
+ // TODO: Find a more elegant solution here sometime...
+ codeSnippet = fieldMap.size() > 0 ? Utils.createSpaces(42) + "," + cr : "";
+ // </cringe>
+ codeSnippet += fieldMap.parseFieldMap(mbPassedParamListGenerateMethod,
+ mbMangledPassedParamListGenerateMethod, 42, 4, this);
+ }
else if (token.compareTo("${mb_field_body_initialize}") == 0)
{
codeSnippet = fieldMap.parseFieldMap(mbBodyInitGenerateMethod,
@@ -712,16 +735,12 @@ public class JavaGenerator extends Generator
String indent = Utils.createSpaces(indentSize);
StringBuffer sb = new StringBuffer();
- Iterator<Integer> iItr = indexMap.keySet().iterator();
- while (iItr.hasNext())
+ for (Integer index : indexMap.keySet())
{
- int index = iItr.next();
AmqpVersionSet versionSet = indexMap.get(index);
- Iterator<AmqpVersion> vItr = versionSet.iterator();
- while (vItr.hasNext())
+ for (AmqpVersion version : versionSet)
{
- AmqpVersion version = vItr.next();
- sb.append(indent + mapName + ".put(\"" + version.toString() + "\", " + index + ");" + cr);
+ sb.append(indent + mapName + "( (byte) " + version.getMajor() +", (byte) " + version.getMinor() + ", " + index + ");" + cr);
}
}
return sb.toString();
@@ -746,12 +765,12 @@ public class JavaGenerator extends Generator
{
int classIndex = findIndex(thisClass.indexMap, version);
int methodIndex = findIndex(method.indexMap, version);
- sb.append(indent + "classIDMethodIDVersionBodyMap.put(" + cr);
- sb.append(indent + tab + "createMapKey((short)" + classIndex +
- ", (short)" + methodIndex + ", (byte)" + version.getMajor() +
- ", (byte)" + version.getMinor() + "), " + cr);
+ sb.append(indent + "registerMethod(" + cr);
+ sb.append(indent + tab + "(short)" + classIndex +
+ ", (short)" + methodIndex + ", (byte)" + version.getMajor() +
+ ", (byte)" + version.getMinor() + ", " + cr);
sb.append(indent + tab + Utils.firstUpper(thisClass.name) +
- Utils.firstUpper(method.name) + "Body.class);" + cr);
+ Utils.firstUpper(method.name) + "Body.getFactory());" + cr);
}
catch (Exception e) {} // Ignore
}
@@ -924,6 +943,15 @@ public class JavaGenerator extends Generator
(nextFlag ? "," : "") + " // AMQP version(s): " + versionSet + cr;
}
+
+ protected String generateMbPassedParamList(String codeType, AmqpField field,
+ AmqpVersionSet versionSet, int indentSize, int tabSize, boolean nextFlag)
+ {
+ return Utils.createSpaces(indentSize) + field.name +
+ (nextFlag ? "," : "") + " // AMQP version(s): " + versionSet + cr;
+ }
+
+
protected String generateMbMangledParamList(AmqpField field, int indentSize,
int tabSize, boolean nextFlag)
throws AmqpTypeMappingException
@@ -943,10 +971,29 @@ public class JavaGenerator extends Generator
return sb.toString();
}
+ protected String generateMbMangledPassedParamList(AmqpField field, int indentSize,
+ int tabSize, boolean nextFlag)
+ throws AmqpTypeMappingException
+ {
+ StringBuffer sb = new StringBuffer();
+ Iterator<String> dItr = field.domainMap.keySet().iterator();
+ int domainCntr = 0;
+ while (dItr.hasNext())
+ {
+ String domainName = dItr.next();
+ AmqpVersionSet versionSet = field.domainMap.get(domainName);
+ sb.append(Utils.createSpaces(indentSize) + field.name + "_" +
+ (domainCntr++) + (nextFlag ? "," : "") + " // AMQP version(s): " +
+ versionSet + cr);
+ }
+ return sb.toString();
+ }
+
+
protected String generateMbBodyInit(String codeType, AmqpField field,
AmqpVersionSet versionSet, int indentSize, int tabSize, boolean nextFlag)
{
- return Utils.createSpaces(indentSize) + "bodyFrame." + field.name + " = " + field.name +
+ return Utils.createSpaces(indentSize) + "this." + field.name + " = " + field.name +
";" + cr;
}
@@ -1004,23 +1051,26 @@ public class JavaGenerator extends Generator
int ordinal, int indentSize, int tabSize)
{
String indent = Utils.createSpaces(indentSize);
- String bitArrayName = "bitArray_" + ordinal;
- StringBuffer sb = new StringBuffer(indent + "boolean[] " + bitArrayName +
- " = new boolean[] { ");
- for (int i=0; i<bitFieldList.size(); i++)
+
+ StringBuilder sb = new StringBuilder();
+ int i = 0;
+ while(i <bitFieldList.size())
{
- if (i != 0)
+
+ StringBuilder line = new StringBuilder();
+
+ for (int j=0; i<bitFieldList.size() && j<8; i++, j++)
{
- if ((i + 3) % 6 == 0)
- sb.append("," + cr + indent + Utils.createSpaces(tabSize));
- else
- sb.append(", ");
+ if (j != 0)
+ {
+ line.append(", ");
+ }
+ line.append(bitFieldList.get(i));
}
- sb.append(bitFieldList.get(i));
+
+ sb.append(indent +
+ typeMap.get("bit").encodeExpression.replaceAll("#", line.toString()) + ";" + cr);
}
- sb.append(" };" + cr);
- sb.append(Utils.createSpaces(indentSize) +
- typeMap.get("bit").encodeExpression.replaceAll("#", bitArrayName) + ";" + cr);
return sb.toString();
}
@@ -1038,14 +1088,25 @@ public class JavaGenerator extends Generator
int ordinal, int indentSize, int tabSize)
{
String indent = Utils.createSpaces(indentSize);
- String bitArrayName = "bitArray_" + ordinal;
- StringBuffer sb = new StringBuffer();
- sb.append(indent +
- typeMap.get("bit").decodeExpression.replaceAll("#", "boolean[] " + bitArrayName) +
- ";" + cr);
- for (int i=0; i<bitFieldList.size(); i++)
+
+ StringBuilder sb = new StringBuilder(indent);
+ // Multiple occurrences of byte value blocks will result in multiple declarations
+ // unless each is named uniquely.
+ String varName = "packedValue_" + ordinal;
+ sb.append("byte " + varName + ";");
+ sb.append(cr);
+
+ // RG HERE!
+
+ int i = 0;
+ while(i < bitFieldList.size())
{
- sb.append(indent + bitFieldList.get(i) + " = " + bitArrayName + "[" + i + "];" + cr);
+ sb.append(indent + varName + " = EncodingUtils.readByte(buffer);" + cr);
+
+ for(int j = 0; i < bitFieldList.size() && j < 8; i++, j++)
+ {
+ sb.append(indent + bitFieldList.get(i) + " = ( " + varName + " & (byte) (1 << " + j + ") ) != 0;" + cr);
+ }
}
return sb.toString();
}
diff --git a/gentools/src/org/apache/qpid/gentools/Main.java b/gentools/src/org/apache/qpid/gentools/Main.java
index 3ba6801375..e8c8a80a26 100644
--- a/gentools/src/org/apache/qpid/gentools/Main.java
+++ b/gentools/src/org/apache/qpid/gentools/Main.java
@@ -38,8 +38,11 @@ public class Main
{
private static final String defaultOutDir = ".." + Utils.fileSeparator + "gen";
private static final String defaultCppTemplateDir = ".." + Utils.fileSeparator + "templ.cpp";
+ private static final String defaultDotnetTemplateDir = ".." + Utils.fileSeparator + "templ.net";
private static final String defaultJavaTemplateDir = ".." + Utils.fileSeparator + "templ.java";
+ private enum GeneratorLangEnum { CPP, DOTNET, JAVA }
+
private DocumentBuilder docBuilder;
private AmqpVersionSet versionSet;
private Generator generator;
@@ -49,7 +52,7 @@ public class Main
private String outDir;
private String tmplDir;
- private boolean javaFlag;
+ private GeneratorLangEnum generatorLang;
private ArrayList<String> xmlFiles;
private File[] modelTemplateFiles;
private File[] classTemplateFiles;
@@ -81,13 +84,20 @@ public class Main
// 0. Initialize
outDir = defaultOutDir;
tmplDir = null;
- javaFlag = true;
+ generatorLang = GeneratorLangEnum.CPP; // Default generation language
xmlFiles.clear();
processArgs(args);
- if (javaFlag)
- prepareJava();
- else
+ switch (generatorLang)
+ {
+ case JAVA:
+ prepareJava();
+ break;
+ case DOTNET:
+ prepareDotnet();
+ break;
+ default:
prepareCpp();
+ }
if (modelTemplateFiles.length == 0 && classTemplateFiles.length == 0 &&
methodTemplateFiles.length == 0 && fieldTemplateFiles.length == 0)
@@ -128,11 +138,15 @@ public class Main
{
case 'c':
case 'C':
- javaFlag = false;
+ generatorLang = GeneratorLangEnum.CPP;
break;
case 'j':
case 'J':
- javaFlag = true;
+ generatorLang = GeneratorLangEnum.JAVA;
+ break;
+ case 'n':
+ case 'N':
+ generatorLang = GeneratorLangEnum.DOTNET;
break;
case 'o':
case 'O':
@@ -182,6 +196,30 @@ public class Main
};
}
+ private void prepareDotnet()
+ {
+ if (tmplDir == null)
+ tmplDir = defaultDotnetTemplateDir;
+ System.out.println(".NET generation mode.");
+ generator = new DotnetGenerator(versionSet);
+ constants = new AmqpConstantSet(generator);
+ domainMap = new AmqpDomainMap(generator);
+ model = new AmqpModel(generator);
+ // TODO: Add templated that should be handled in here...
+ modelTemplateFiles = new File[]
+ {
+// new File(tmplDir + Utils.fileSeparator + "XXXClass.tmpl"),
+ };
+ classTemplateFiles = new File[]
+ {
+// new File(tmplDir + Utils.fileSeparator + "XXXClass.tmpl"),
+ };
+ methodTemplateFiles = new File[]
+ {
+// new File(tmplDir + Utils.fileSeparator + "XXXClass.tmpl"),
+ };
+ }
+
private void prepareCpp()
{
if (tmplDir == null)
@@ -293,6 +331,7 @@ public class Main
System.out.println("Usage: Main -c|-j [-o outDir] [-t tmplDir] XMLfile [XMLfile ...]");
System.out.println(" where -c: Generate C++.");
System.out.println(" -j: Generate Java.");
+ System.out.println(" -n: Generate .NET.");
System.out.println(" -o outDir: Use outDir as the output dir (default=\"" + defaultOutDir + "\").");
System.out.println(" -t tmplDir: Find templates in tmplDir.");
System.out.println(" Defaults: \"" + defaultCppTemplateDir + "\" for C++;");
diff --git a/gentools/templ.java/MethodBodyClass.tmpl b/gentools/templ.java/MethodBodyClass.tmpl
index 4693232b26..eb7a62ed0e 100644
--- a/gentools/templ.java/MethodBodyClass.tmpl
+++ b/gentools/templ.java/MethodBodyClass.tmpl
@@ -28,36 +28,107 @@
package org.apache.qpid.framing;
-import java.util.TreeMap;
+import java.util.HashMap;
+import java.util.ArrayList;
+import java.util.Arrays;
import org.apache.mina.common.ByteBuffer;
public class ${CLASS}${METHOD}Body extends AMQMethodBody implements EncodableAMQDataBlock
{
- public static final TreeMap<String, Integer> classIdMap = new TreeMap<String, Integer>();
- public static final TreeMap<String, Integer> methodIdMap = new TreeMap<String, Integer>();
+ private static final AMQMethodBodyInstanceFactory factory = new AMQMethodBodyInstanceFactory()
+ {
+ public AMQMethodBody newInstance(byte major, byte minor, ByteBuffer in, long size) throws AMQFrameDecodingException
+ {
+ return new ${CLASS}${METHOD}Body(major, minor, in);
+ }
+
+ public AMQMethodBody newInstance(byte major, byte minor, int clazzID, int methodID, ByteBuffer in, long size) throws AMQFrameDecodingException
+ {
+ return new ${CLASS}${METHOD}Body(major, minor, clazzID, methodID, in);
+ }
+
+ };
+
+ public static AMQMethodBodyInstanceFactory getFactory()
+ {
+ return factory;
+ }
+ public static HashMap<Integer, Integer> classIdMap = new HashMap<Integer, Integer>();
+ public static HashMap<Integer, Integer> methodIdMap = new HashMap<Integer, Integer>();
+
+ private static void registerMethodId(byte major, byte minor, int methodId)
+ {
+ methodIdMap.put((0xff & (int) major) | ((0xff & (int) minor)<<8), methodId);
+ }
+
+ private static void registerClassId(byte major, byte minor, int classId)
+ {
+ classIdMap.put((0xff & (int) major) | ((0xff & (int) minor)<<8), classId);
+ }
+
+
static
{
-${CLASS_ID_INIT}
-${METHOD_ID_INIT}
+ ${CLASS_ID_INIT}
+ ${METHOD_ID_INIT}
}
// Fields declared in specification
%{FLIST} ${field_declaration}
+ private final int _clazz;
+ private final int _method;
+
+
// Constructor
- public ${CLASS}${METHOD}Body(byte major, byte minor)
+
+ public ${CLASS}${METHOD}Body(byte major, byte minor, ByteBuffer buffer) throws AMQFrameDecodingException
+ {
+ this(major, minor, getClazz(major,minor), getMethod(major,minor), buffer);
+ }
+
+ public ${CLASS}${METHOD}Body(byte major, byte minor, int clazzID, int methodID, ByteBuffer buffer) throws AMQFrameDecodingException
{
super(major, minor);
+ _clazz = clazzID;
+ _method = methodID;
+%{FLIST} ${mb_field_decode}
+ }
+
+ public ${CLASS}${METHOD}Body(byte major, byte minor, int clazzID, int methodID
+%{FLIST} ${mb_field_parameter_list}
+ )
+ {
+ super(major, minor);
+ _clazz = getClazz(major,minor);
+ _method = getMethod(major,minor);
+%{FLIST} ${mb_field_body_initialize}
+ }
+
+ public int getClazz()
+ {
+ return _clazz;
+ }
+
+ public int getMethod()
+ {
+ return _method;
}
- public int getClazz() { return classIdMap.get(major + "-" + minor); }
- public int getMethod() { return methodIdMap.get(major + "-" + minor); }
- public static int getClazz(byte major, byte minor) { return classIdMap.get(major + "-" + minor); }
- public static int getMethod(byte major, byte minor) { return methodIdMap.get(major + "-" + minor); }
-
- // Field methods
+ public static int getClazz(byte major, byte minor)
+ {
+ return classIdMap.get((0xff & (int) major) | ((0xff & (int) minor)<<8));
+ }
+
+ public static int getMethod(byte major, byte minor)
+ {
+ return methodIdMap.get((0xff & (int) major) | ((0xff & (int) minor)<<8));
+ }
+
+
+ // Field methods
%{FLIST} ${mb_field_get_method}
public int getBodySize()
@@ -88,17 +159,24 @@ ${METHOD_ID_INIT}
%{FLIST} ${mb_field_parameter_list}
)
{
- ${CLASS}${METHOD}Body bodyFrame = new ${CLASS}${METHOD}Body(major, minor);
-%{FLIST} ${mb_field_body_initialize}
+ return createMethodBody(major, minor, getClazz(major, minor), getMethod(major, minor)
+%{FLIST} ${mb_field_passed_parameter_list}
+ );
+ }
- return bodyFrame;
+ public static ${CLASS}${METHOD}Body createMethodBody(byte major, byte minor, int clazzID, int methodID
+%{FLIST} ${mb_field_parameter_list}
+ )
+ {
+ return new ${CLASS}${METHOD}Body(major, minor, clazzID, methodID
+%{FLIST} ${mb_field_passed_parameter_list}
+ );
}
public ${CLASS}${METHOD}Body copy()
{
- ${CLASS}${METHOD}Body bodyFrame = new ${CLASS}${METHOD}Body(major, minor);
-%{FLIST} ${mb_field_body_initialize}
-
- return bodyFrame;
+ return new ${CLASS}${METHOD}Body(major, minor, getClazz(major, minor), getMethod(major, minor)
+%{FLIST} ${mb_field_passed_parameter_list}
+ );
}
}
diff --git a/gentools/templ.java/MethodRegistryClass.tmpl b/gentools/templ.java/MethodRegistryClass.tmpl
index 0f15918f90..c3f11d9f5a 100644
--- a/gentools/templ.java/MethodRegistryClass.tmpl
+++ b/gentools/templ.java/MethodRegistryClass.tmpl
@@ -31,50 +31,101 @@ package org.apache.qpid.framing;
import java.util.HashMap;
import java.lang.reflect.Constructor;
import org.apache.log4j.Logger;
+import org.apache.mina.common.ByteBuffer;
-class MainRegistry
+public class MainRegistry
{
+ private static final HashMap<Long, AMQMethodBodyInstanceFactory> classIDMethodIDVersionBodyMap = new HashMap<Long, AMQMethodBodyInstanceFactory>();
+
+
private static final Logger _log = Logger.getLogger(MainRegistry.class);
- private static HashMap<Long, Class> classIDMethodIDVersionBodyMap = new HashMap<Long, Class>();
+
+ private static final int DEFAULT_MINOR_VERSION_COUNT = 10;
+ private static final int DEFAULT_MAJOR_VERSION_COUNT = 10;
+
+ private static VersionSpecificRegistry[][] _specificRegistries = new VersionSpecificRegistry[DEFAULT_MAJOR_VERSION_COUNT][];
+
static
{
%{CLIST} ${reg_map_put_method}
}
- public static AMQMethodBody get(short classID, short methodID, byte major, byte minor)
+ public static AMQMethodBody get(short classID, short methodID, byte major, byte minor, ByteBuffer in, long size)
throws AMQFrameDecodingException
{
- Class bodyClass = classIDMethodIDVersionBodyMap.get(
- createMapKey(classID, methodID, major, minor));
- if (bodyClass == null)
- {
- throw new AMQFrameDecodingException(_log,
- "Unable to find a suitable decoder for class " + classID + " and method " +
- methodID + " in AMQP version " + major + "-" + minor + ".");
- }
- try
- {
- Constructor initFn = bodyClass.getConstructor(byte.class, byte.class);
- return (AMQMethodBody) initFn.newInstance(major, minor);
- }
- catch (Exception e)
- {
- throw new AMQFrameDecodingException(_log,
- "Unable to instantiate body class for class " + classID + " and method " +
- methodID + " in AMQP version " + major + "-" + minor + " : " + e, e);
- }
+ VersionSpecificRegistry registry = getVersionSpecificRegistry(major, minor);
+ AMQMethodBodyInstanceFactory bodyFactory = registry.getMethodBody(classID,methodID);
+
+ if (bodyFactory == null)
+ {
+ throw new AMQFrameDecodingException(_log,
+ "Unable to find a suitable decoder for class " + classID + " and method " +
+ methodID + " in AMQP version " + major + "-" + minor + ".");
+ }
+ return bodyFactory.newInstance(major, minor, in, size);
+
+
}
+
+ public static VersionSpecificRegistry getVersionSpecificRegistry(byte major, byte minor)
+ {
+ try
+ {
+ return _specificRegistries[(int)major][(int)minor];
+ }
+ catch (IndexOutOfBoundsException e)
+ {
+ return null;
+ }
+ catch (NullPointerException e)
+ {
+ return null;
+ }
+
+
+ }
- private static Long createMapKey(short classID, short methodID, byte major, byte minor)
- {
- /**
- * Mapping of 4 components into a guaranteed unique key:
- * MSB LSB
- * +----+----+----+----+----+----+-----+-----+
- * | 0 | classID |methodID |major|minor|
- * +----+----+----+----+----+----+-----+-----+
- */
- return new Long(((long)classID << 32) + ((long)methodID << 16) + ((long)major << 8) + minor);
+ private static VersionSpecificRegistry addVersionSpecificRegistry(byte major, byte minor)
+ {
+ VersionSpecificRegistry[][] registries = _specificRegistries;
+ if(major >= registries.length)
+ {
+ _specificRegistries = new VersionSpecificRegistry[(int)major + 1][];
+ System.arraycopy(registries, 0, _specificRegistries, 0, registries.length);
+ registries = _specificRegistries;
+ }
+ if(registries[major] == null)
+ {
+ registries[major] = new VersionSpecificRegistry[ minor >= DEFAULT_MINOR_VERSION_COUNT ? minor + 1 : DEFAULT_MINOR_VERSION_COUNT ];
+ }
+ else if(registries[major].length <= minor)
+ {
+ VersionSpecificRegistry[] minorArray = registries[major];
+ registries[major] = new VersionSpecificRegistry[ minor + 1 ];
+ System.arraycopy(minorArray, 0, registries[major], 0, minorArray.length);
+
+ }
+
+ VersionSpecificRegistry newRegistry = new VersionSpecificRegistry(major,minor);
+
+ registries[major][minor] = newRegistry;
+
+ return newRegistry;
+ }
+
+ private static void registerMethod(short classID, short methodID, byte major, byte minor, AMQMethodBodyInstanceFactory instanceFactory )
+ {
+ VersionSpecificRegistry registry = getVersionSpecificRegistry(major,minor);
+ if(registry == null)
+ {
+ registry = addVersionSpecificRegistry(major,minor);
+
+ }
+
+ registry.registerMethod(classID, methodID, instanceFactory);
+
}
+
+
}
diff --git a/java/broker/bin/qpid-server-bdb.bat b/java/broker/bin/qpid-server-bdb.bat
new file mode 100644
index 0000000000..5c8b74e163
--- /dev/null
+++ b/java/broker/bin/qpid-server-bdb.bat
@@ -0,0 +1,3 @@
+set BDBSTORE_HOME=c:\qpid\trunk\java\bdbstore
+set QPID_MODULE_JARS=%BDBSTORE_HOME%\target\qpid-bdbstore-1.0-incubating-M2-SNAPSHOT.jar;%BDBSTORE_HOME%\lib\bdb\je-3.1.0.jar
+.\qpid-server.bat \ No newline at end of file
diff --git a/java/broker/bin/qpid-server.bat b/java/broker/bin/qpid-server.bat
index b839cc72d8..a99022cd2d 100644
--- a/java/broker/bin/qpid-server.bat
+++ b/java/broker/bin/qpid-server.bat
@@ -17,7 +17,7 @@
@REM under the License.
@REM
-@echo off
+echo off
REM Script to run the Qpid Java Broker
rem Guess QPID_HOME if not defined
@@ -60,9 +60,11 @@ set QPID_ARGS=%QPID_ARGS% %1
shift
goto loop
+rem QPID_OPTS intended to hold any -D props for use
+rem user must enclose any value for QPID_OPTS in double quotes
:runCommand
set LAUNCH_JAR=%QPID_HOME%\lib\qpid-incubating.jar
set MODULE_JARS=%QPID_MODULE_JARS%
-"%JAVA_HOME%\bin\java" -server -Xmx1024m -DQPID_HOME="%QPID_HOME%" -cp "%LAUNCH_JAR%;%MODULE_JARS%" org.apache.qpid.server.Main %QPID_ARGS%
+"%JAVA_HOME%\bin\java" -server -Xmx1024m %QPID_OPTS% -DQPID_HOME="%QPID_HOME%" -cp "%LAUNCH_JAR%;%MODULE_JARS%" org.apache.qpid.server.Main %QPID_ARGS%
:end
diff --git a/java/broker/distribution/pom.xml b/java/broker/distribution/pom.xml
new file mode 100644
index 0000000000..9875e9bf2b
--- /dev/null
+++ b/java/broker/distribution/pom.xml
@@ -0,0 +1,153 @@
+<!--
+ 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.
+ -->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>org.apache.qpid</groupId>
+ <artifactId>qpid-broker-distribution</artifactId>
+ <packaging>jar</packaging>
+ <version>1.0-incubating-M2-SNAPSHOT</version>
+ <name>Qpid Broker Distributions</name>
+ <url>http://cwiki.apache.org/confluence/display/qpid</url>
+
+ <parent>
+ <groupId>org.apache.qpid</groupId>
+ <artifactId>qpid</artifactId>
+ <version>1.0-incubating-M2-SNAPSHOT</version>
+ </parent>
+
+ <properties>
+ <topDirectoryLocation>..</topDirectoryLocation>
+ <java.source.version>1.5</java.source.version>
+ <qpid.version>${pom.version}</qpid.version>
+ <qpid.targetDir>${project.build.directory}</qpid.targetDir>
+ </properties>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.qpid</groupId>
+ <artifactId>qpid-broker</artifactId>
+ <type>jar</type>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <pluginManagement>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <configuration>
+ <source>${java.source.version}</source>
+ <target>${java.source.version}</target>
+ </configuration>
+ </plugin>
+
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-assembly-plugin</artifactId>
+ <version>${assembly.version}</version>
+ <configuration>
+ <descriptors>
+ <descriptor>src/main/assembly/broker-bin.xml</descriptor>
+ </descriptors>
+ <finalName>qpid-${pom.version}</finalName>
+ <outputDirectory>${qpid.targetDir}</outputDirectory>
+ <tarLongFileMode>gnu</tarLongFileMode>
+ </configuration>
+ </plugin>
+
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-jar-plugin</artifactId>
+ <configuration>
+ <finalName>qpid-incubating</finalName>
+ <archive>
+ <manifest>
+ <addClasspath>true</addClasspath>
+ </manifest>
+ </archive>
+ </configuration>
+ </plugin>
+
+ </plugins>
+ </pluginManagement>
+
+ <plugins>
+ <plugin>
+ <artifactId>maven-assembly-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>distribution-package</id>
+ <phase>package</phase>
+ <goals>
+ <goal>single</goal>
+ </goals>
+ <configuration>
+ <descriptors>
+ <descriptor>src/main/assembly/broker-bin.xml</descriptor>
+ <descriptor>src/main/assembly/broker-src.xml</descriptor>
+ </descriptors>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+
+ </build>
+
+ <profiles>
+ <profile>
+ <id>tests</id>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.qpid</groupId>
+ <artifactId>qpid-broker</artifactId>
+ <type>test-jar</type>
+ <version>${project.version}</version>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <artifactId>maven-assembly-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>distribution-package</id>
+ <phase>package</phase>
+ <goals>
+ <goal>single</goal>
+ </goals>
+ <configuration>
+ <descriptors>
+ <descriptor>src/main/assembly/broker-bin-tests.xml</descriptor>
+ </descriptors>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+
+ </build>
+ </profile>
+ </profiles>
+</project>
diff --git a/java/broker/distribution/src/main/assembly/broker-bin-tests.xml b/java/broker/distribution/src/main/assembly/broker-bin-tests.xml
new file mode 100644
index 0000000000..fa017d6232
--- /dev/null
+++ b/java/broker/distribution/src/main/assembly/broker-bin-tests.xml
@@ -0,0 +1,116 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ * 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.
+-->
+<assembly>
+ <id>java-broker-bin-with-tests</id>
+ <includeBaseDirectory>false</includeBaseDirectory>
+ <formats>
+ <format>tar.gz</format>
+ <format>zip</format>
+ </formats>
+
+ <fileSets>
+ <fileSet>
+ <!-- Apache license files -->
+ <directory>../../resources</directory>
+ <outputDirectory>qpid-${qpid.version}</outputDirectory>
+ <includes>
+ <include>DISCLAIMER</include>
+ <include>LICENSE.txt</include>
+ <include>NOTICE.txt</include>
+ <include>README.txt</include>
+ </includes>
+ </fileSet>
+
+ <fileSet>
+ <directory>../../release-docs</directory>
+ <outputDirectory>qpid-${qpid.version}/docs</outputDirectory>
+ <includes>
+ <include>RELEASE_NOTES.txt</include>
+ </includes>
+ </fileSet>
+
+ <!-- Include easy access to test source-->
+ <fileSet>
+ <directory>../src/test</directory>
+ <outputDirectory>qpid-${qpid.version}/src</outputDirectory>
+ <includes>
+ <include>**/*.java</include>
+ </includes>
+ </fileSet>
+
+ <!-- Execution Scripts -->
+ <fileSet>
+ <directory>../bin/</directory>
+ <outputDirectory>qpid-${qpid.version}/bin</outputDirectory>
+ <includes>
+ <include>**/*</include>
+ </includes>
+ <fileMode>777</fileMode> <!-- RWX -->
+ </fileSet>
+
+ <!-- Configuration -->
+ <fileSet>
+ <directory>../etc/</directory>
+ <outputDirectory>qpid-${qpid.version}/etc</outputDirectory>
+ <includes>
+ <include>**/*</include>
+ </includes>
+ <fileMode>420</fileMode>
+ </fileSet>
+
+ <!-- Metadata Jar -->
+ <fileSet>
+ <directory>target</directory>
+ <outputDirectory>qpid-${qpid.version}/lib</outputDirectory>
+ <includes>
+ <include>qpid-incubating.jar</include>
+ </includes>
+ </fileSet>
+ </fileSets>
+
+
+ <files>
+ <!-- Common Run scripts -->
+ <file>
+ <source>../../common/bin/qpid-run</source>
+ <outputDirectory>qpid-${qpid.version}/bin</outputDirectory>
+ <destName>qpid-run</destName>
+ <fileMode>493</fileMode>
+ </file>
+
+ <!-- Common Configuration -->
+ <file>
+ <source>../../common/etc/qpid-run.conf</source>
+ <outputDirectory>qpid-${qpid.version}/etc</outputDirectory>
+ <destName>qpid-run.conf</destName>
+ <fileMode>420</fileMode>
+ </file>
+ </files>
+
+ <dependencySets>
+ <dependencySet>
+ <outputDirectory>qpid-${qpid.version}/lib</outputDirectory>
+ <unpack>false</unpack>
+ <excludes>
+ <exclude>org.apache.qpid:qpid-broker-distribution</exclude>
+ </excludes>
+ </dependencySet>
+ </dependencySets>
+</assembly>
diff --git a/java/broker/distribution/src/main/assembly/broker-bin.xml b/java/broker/distribution/src/main/assembly/broker-bin.xml
new file mode 100644
index 0000000000..4a7343660d
--- /dev/null
+++ b/java/broker/distribution/src/main/assembly/broker-bin.xml
@@ -0,0 +1,171 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ * 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.
+-->
+<assembly>
+ <!-- id typically identifies the "type" (src vs bin etc) of the assembly -->
+ <id>java-broker-bin</id>
+ <includeBaseDirectory>false</includeBaseDirectory>
+ <formats>
+ <format>tar.gz</format>
+ <format>zip</format>
+ </formats>
+
+ <fileSets>
+ <!-- Apache Licensing -->
+ <fileSet>
+ <directory>../../resources</directory>
+ <outputDirectory>qpid-${qpid.version}</outputDirectory>
+ <includes>
+ <include>DISCLAIMER</include>
+ <include>LICENSE.txt</include>
+ <include>NOTICE.txt</include>
+ <include>README.txt</include>
+ </includes>
+ </fileSet>
+ <fileSet>
+ <directory>../..</directory>
+ <outputDirectory>qpid-${qpid.version}</outputDirectory>
+ <includes>
+ <include>*.txt</include>
+ </includes>
+ </fileSet>
+ <fileSet>
+ <directory>../../src/main/release-docs</directory>
+ <outputDirectory>qpid-${qpid.version}/docs</outputDirectory>
+ <includes>
+ <include>RELEASE_NOTES.txt</include>
+ </includes>
+ </fileSet>
+
+ <!-- Metadata Jar -->
+ <fileSet>
+ <directory>target</directory>
+ <outputDirectory>qpid-${qpid.version}/lib</outputDirectory>
+ <includes>
+ <include>qpid-incubating.jar</include>
+ </includes>
+ </fileSet>
+ </fileSets>
+ <files>
+ <!-- due to a bug in the assembly plugin (MASSEMBLY-153) you have
+ to use decimal numbers to specify fileMode -->
+ <file>
+ <source>../../common/etc/qpid-run.conf</source>
+ <outputDirectory>qpid-${qpid.version}/etc</outputDirectory>
+ <destName>qpid-run.conf</destName>
+ <fileMode>420</fileMode>
+ </file>
+ <file>
+ <source>../etc/config.xml</source>
+ <outputDirectory>qpid-${qpid.version}/etc</outputDirectory>
+ <destName>config.xml</destName>
+ <fileMode>420</fileMode>
+ </file>
+ <file>
+ <source>../etc/log4j.xml</source>
+ <outputDirectory>qpid-${qpid.version}/etc</outputDirectory>
+ <destName>log4j.xml</destName>
+ <fileMode>420</fileMode>
+ </file>
+ <file>
+ <source>../etc/passwd</source>
+ <outputDirectory>qpid-${qpid.version}/etc</outputDirectory>
+ <destName>passwd</destName>
+ <fileMode>420</fileMode>
+ </file>
+ <file>
+ <source>../etc/qpid-server.conf</source>
+ <outputDirectory>qpid-${qpid.version}/etc</outputDirectory>
+ <destName>qpid-server.conf</destName>
+ <fileMode>420</fileMode>
+ </file>
+ <file>
+ <source>../etc/virtualhosts.xml</source>
+ <outputDirectory>qpid-${qpid.version}/etc</outputDirectory>
+ <destName>virtualhosts.xml</destName>
+ <fileMode>420</fileMode>
+ </file>
+ <file>
+ <source>../../common/bin/qpid-run</source>
+ <outputDirectory>qpid-${qpid.version}/bin</outputDirectory>
+ <destName>qpid-run</destName>
+ <fileMode>473</fileMode>
+ </file>
+ <file>
+ <source>../bin/qpid-server</source>
+ <outputDirectory>qpid-${qpid.version}/bin</outputDirectory>
+ <destName>qpid-server</destName>
+ <fileMode>473</fileMode>
+ </file>
+ <file>
+ <source>../bin/qpid-server.bat</source>
+ <outputDirectory>qpid-${qpid.version}/bin</outputDirectory>
+ <destName>qpid-server.bat</destName>
+ <fileMode>473</fileMode>
+ </file>
+ <file>
+ <source>../bin/run.bat</source>
+ <outputDirectory>qpid-${qpid.version}/bin</outputDirectory>
+ <destName>run.bat</destName>
+ <fileMode>473</fileMode>
+ </file>
+ <file>
+ <source>../bin/run.sh</source>
+ <outputDirectory>qpid-${qpid.version}/bin</outputDirectory>
+ <destName>run.sh</destName>
+ <fileMode>473</fileMode>
+ </file>
+ <file>
+ <source>../bin/runAll</source>
+ <outputDirectory>qpid-${qpid.version}/bin</outputDirectory>
+ <destName>runAll</destName>
+ <fileMode>473</fileMode>
+ </file>
+ </files>
+
+ <dependencySets>
+ <dependencySet>
+ <outputDirectory>qpid-${qpid.version}/lib</outputDirectory>
+ <unpack>false</unpack>
+ <!-- This needs to be tidied up QPID-280 -->
+ <excludes>
+ <exclude>org.apache.qpid:qpid-broker-distribution</exclude>
+ <exclude>org.apache.qpid.management:org.apache.qpid.management.ui</exclude>
+ <exclude>org.eclipse.core:org.eclipse.core.commands</exclude>
+ <exclude>org.eclipse.core:org.eclipse.core.contenttype</exclude>
+ <exclude>org.eclipse.core:org.eclipse.core.expressions</exclude>
+ <exclude>org.eclipse.core:org.eclipse.core.jobs</exclude>
+ <exclude>org.eclipse.core:org.eclipse.core.runtime</exclude>
+ <exclude>org.eclipse.core:org.eclipse.core.runtime.compatibility.auth</exclude>
+ <exclude>org.eclipse.core:org.eclipse.core.runtime.compatibility.registry</exclude>
+ <exclude>org.eclipse.equinox:org.eclipse.equinox.common</exclude>
+ <exclude>org.eclipse.equinox:org.eclipse.equinox.preferences</exclude>
+ <exclude>org.eclipse.equinox:org.eclipse.equinox.registry</exclude>
+ <exclude>org.eclipse.help:org.eclipse.help</exclude>
+ <exclude>org.eclipse.jface:org.eclipse.jface</exclude>
+ <exclude>org.eclipse.osgi:org.eclipse.osgi</exclude>
+ <exclude>org.eclipse.swt:org.eclipse.swt</exclude>
+ <exclude>org.eclipse.swt:org.eclipse.swt.win32.win32.x86</exclude>
+ <exclude>org.eclipse.ui:org.eclipse.ui</exclude>
+ <exclude>org.eclipse.ui:org.eclipse.ui.forms</exclude>
+ <exclude>org.eclipse.ui:org.eclipse.ui.workbench</exclude>
+ </excludes>
+ </dependencySet>
+ </dependencySets>
+</assembly>
diff --git a/java/broker/distribution/src/main/assembly/broker-src.xml b/java/broker/distribution/src/main/assembly/broker-src.xml
new file mode 100644
index 0000000000..28a22c3851
--- /dev/null
+++ b/java/broker/distribution/src/main/assembly/broker-src.xml
@@ -0,0 +1,78 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ * 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.
+-->
+<assembly>
+ <!-- id typically identifies the "type" (src vs bin etc) of the assembly -->
+ <id>java-broker-src</id>
+ <includeBaseDirectory>false</includeBaseDirectory>
+ <formats>
+ <format>tar.gz</format>
+ <format>zip</format>
+ </formats>
+
+ <fileSets>
+ <!-- Apache Licensing -->
+ <fileSet>
+ <directory>../../resources</directory>
+ <outputDirectory>qpid-${qpid.version}-src</outputDirectory>
+ <includes>
+ <include>DISCLAIMER</include>
+ <include>LICENSE.txt</include>
+ <include>licenses/*.*</include>
+ <include>NOTICE.txt</include>
+ <include>README.txt</include>
+ <include>BUILDING.txt</include>
+ </includes>
+ </fileSet>
+ <!-- Broker source -->
+ <fileSet>
+ <directory>..</directory>
+ <outputDirectory>qpid-${qpid.version}-src</outputDirectory>
+ <includes>
+ <include>**/*</include>
+ </includes>
+ <!-- Tidy up wrt to QPID-280 -->
+ <excludes>
+ <exclude>build.xml</exclude>
+ <exclude>distribution/build.xml</exclude>
+ <exclude>benchmark</exclude>
+ <exclude>benchmark/**/*</exclude>
+ <exclude>**/target</exclude>
+ <exclude>**/target/**/*</exclude>
+ <exclude>**/build</exclude>
+ <exclude>**/build/**/*</exclude>
+ <exclude>**/.settings</exclude>
+ <exclude>**/.classpath</exclude>
+ <exclude>**/.project</exclude>
+ <exclude>**/.wtpmodules</exclude>
+ <exclude>**/surefire*</exclude>
+ <exclude>**/cobertura.ser</exclude>
+ <exclude>bin</exclude>
+ <exclude>bin/*</exclude>
+ <exclude>lib</exclude>
+ <exclude>lib/**/*</exclude>
+ <exclude>**/var/journal</exclude>
+ <exclude>**/build.out*</exclude>
+ <exclude>**/eclipse-plugin/bin/**</exclude>
+ <exclude>**/eclipse-plugin/plugins/**</exclude>
+ <exclude>**/eclipse-plugin/src/main/resources/**</exclude>
+ </excludes>
+ </fileSet>
+ </fileSets>
+</assembly>
diff --git a/java/broker/etc/config.xml b/java/broker/etc/config.xml
index 61e0e55138..779a434332 100644
--- a/java/broker/etc/config.xml
+++ b/java/broker/etc/config.xml
@@ -79,6 +79,37 @@
</mechanisms>
</sasl>
</security>
+ <virtualhosts>
+ <virtualhost>
+ <name>localhost</name>
+ <localhost>
+ <store>
+ <!-- <class>org.apache.qpid.server.store.berkeleydb.BDBMessageStore</class> -->
+ <class>org.apache.qpid.server.store.MemoryMessageStore</class>
+ <environment-path>localhost-store</environment-path>
+ </store>
+ </localhost>
+ </virtualhost>
+
+ <virtualhost>
+ <name>development</name>
+ <development>
+ <store>
+ <class>org.apache.qpid.server.store.MemoryMessageStore</class>
+ </store>
+ </development>
+ </virtualhost>
+
+ <virtualhost>
+ <name>test</name>
+ <test>
+ <store>
+ <class>org.apache.qpid.server.store.MemoryMessageStore</class>
+ </store>
+ </test>
+ </virtualhost>
+
+ </virtualhosts>
<heartbeat>
<delay>0</delay>
<timeoutFactor>2.0</timeoutFactor>
@@ -86,8 +117,6 @@
<queue>
<auto_register>true</auto_register>
</queue>
- <store>
- <class>org.apache.qpid.server.store.MemoryMessageStore</class>
- </store>
+
<virtualhosts>${conf}/virtualhosts.xml</virtualhosts>
</broker>
diff --git a/java/broker/etc/log4j.xml b/java/broker/etc/log4j.xml
index 0cfabf8643..425ecd31d5 100644
--- a/java/broker/etc/log4j.xml
+++ b/java/broker/etc/log4j.xml
@@ -8,9 +8,9 @@
- 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
@@ -36,15 +36,28 @@
<param name="ConversionPattern" value="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
</layout>
</appender>
+
+ <!--
+ After merge with trunk, there seems to be considerable confusion over
+ this section, so all have been commented out for now...
+ -->
- <category name="org.apache.qpid.framing">
+ <!--<category name="org.apache.qpid.framing">
<priority value="debug"/>
</category>
- <category name="org.apache.qpid.server.handler">
+ <category name="org.apache.qpid.server.queue">
<priority value="debug"/>
</category>
+ <category name="org.apache.qpid.server.txn">
+ <priority value="debug"/>
+ </category>
+
+ <category name="org.apache.qpid.server.handler">
+ <priority value="debug"/>
+ </category>-->
+
<root>
<priority value="debug"/>
<appender-ref ref="STDOUT"/>
diff --git a/java/broker/etc/virtualhosts.xml b/java/broker/etc/virtualhosts.xml
index de6a8c0682..50cddb5661 100644
--- a/java/broker/etc/virtualhosts.xml
+++ b/java/broker/etc/virtualhosts.xml
@@ -21,7 +21,17 @@
-->
<virtualhosts>
<virtualhost>
- <path>/development</path>
+ <path>localhost</path>
+ <bind>direct://amq.direct//queue</bind>
+ <bind>direct://amq.direct//ping</bind>
+ </virtualhost>
+ <virtualhost>
+ <path>development</path>
+ <bind>direct://amq.direct//queue</bind>
+ <bind>direct://amq.direct//ping</bind>
+ </virtualhost>
+ <virtualhost>
+ <path>test</path>
<bind>direct://amq.direct//queue</bind>
<bind>direct://amq.direct//ping</bind>
</virtualhost>
diff --git a/java/broker/pom.xml b/java/broker/pom.xml
index 92a3d69060..2cf8a563f0 100644
--- a/java/broker/pom.xml
+++ b/java/broker/pom.xml
@@ -37,53 +37,44 @@
</properties>
<dependencies>
+
<dependency>
<groupId>org.apache.qpid</groupId>
<artifactId>qpid-common</artifactId>
</dependency>
+
<dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
</dependency>
+
<dependency>
<groupId>commons-configuration</groupId>
<artifactId>commons-configuration</artifactId>
</dependency>
+
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
</dependency>
- <dependency>
- <groupId>org.apache.geronimo.specs</groupId>
- <artifactId>geronimo-jms_1.1_spec</artifactId>
- </dependency>
- <dependency>
- <groupId>org.apache.mina</groupId>
- <artifactId>mina-filter-ssl</artifactId>
- </dependency>
- <dependency>
- <groupId>org.apache.mina</groupId>
- <artifactId>mina-java5</artifactId>
- </dependency>
- <dependency>
- <groupId>backport-util-concurrent</groupId>
- <artifactId>backport-util-concurrent</artifactId>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-simple</artifactId>
- </dependency>
+
+ <!-- Test Dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
+ <scope>test</scope>
</dependency>
+
<dependency>
<groupId>org.easymock</groupId>
<artifactId>easymockclassextension</artifactId>
+ <scope>test</scope>
</dependency>
+
</dependencies>
<build>
+
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
@@ -128,7 +119,32 @@
</systemProperties>
</configuration>
</plugin>
+
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-jar-plugin</artifactId>
+ <executions>
+ <execution>
+ <phase>package</phase>
+ <goals>
+ <goal>test-jar</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
</plugins>
+
+ <testResources>
+ <testResource>
+ <targetPath>src/</targetPath>
+ <filtering>false</filtering>
+ <directory>src/test/java</directory>
+ <includes>
+ <include>**/*.java</include>
+ </includes>
+ </testResource>
+ </testResources>
+
</build>
</project>
diff --git a/java/broker/src/main/grammar/SelectorParser.jj b/java/broker/src/main/grammar/SelectorParser.jj
index 5553a46e47..736632b352 100644
--- a/java/broker/src/main/grammar/SelectorParser.jj
+++ b/java/broker/src/main/grammar/SelectorParser.jj
@@ -66,8 +66,9 @@ package org.apache.qpid.server.filter.jms.selector;
import java.io.*;
import java.util.*;
-import javax.jms.InvalidSelectorException;
+import org.apache.qpid.AMQInvalidSelectorException;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.server.filter.*;
/**
@@ -81,14 +82,14 @@ public class SelectorParser {
this(new StringReader(""));
}
- public BooleanExpression parse(String sql) throws InvalidSelectorException {
+ public BooleanExpression parse(String sql) throws AMQInvalidSelectorException {
this.ReInit(new StringReader(sql));
try {
return this.JmsSelector();
}
catch (Throwable e) {
- throw (InvalidSelectorException)new InvalidSelectorException(sql).initCause(e);
+ throw (AMQInvalidSelectorException)new AMQInvalidSelectorException(sql).initCause(e);
}
}
@@ -589,7 +590,7 @@ PropertyExpression variable() :
(
t = <ID>
{
- left = new PropertyExpression(t.image);
+ left = new PropertyExpression(new AMQShortString(t.image));
}
)
{
diff --git a/java/broker/src/main/java/org/apache/qpid/server/AMQBrokerManagerMBean.java b/java/broker/src/main/java/org/apache/qpid/server/AMQBrokerManagerMBean.java
index 509f57be7f..204b5674ce 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/AMQBrokerManagerMBean.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/AMQBrokerManagerMBean.java
@@ -30,7 +30,9 @@ import org.apache.qpid.server.exchange.Exchange;
import org.apache.qpid.server.store.MessageStore;
import org.apache.qpid.server.registry.IApplicationRegistry;
import org.apache.qpid.server.registry.ApplicationRegistry;
+import org.apache.qpid.server.virtualhost.VirtualHost;
import org.apache.qpid.AMQException;
+import org.apache.qpid.framing.AMQShortString;
import javax.management.JMException;
import javax.management.MBeanException;
@@ -49,20 +51,28 @@ public class AMQBrokerManagerMBean extends AMQManagedObject implements ManagedBr
private final ExchangeFactory _exchangeFactory;
private final MessageStore _messageStore;
+ private final VirtualHost.VirtualHostMBean _virtualHostMBean;
+
@MBeanConstructor("Creates the Broker Manager MBean")
- public AMQBrokerManagerMBean() throws JMException
+ public AMQBrokerManagerMBean(VirtualHost.VirtualHostMBean virtualHostMBean) throws JMException
{
super(ManagedBroker.class, ManagedBroker.TYPE);
- IApplicationRegistry appRegistry = ApplicationRegistry.getInstance();
- _queueRegistry = appRegistry.getQueueRegistry();
- _exchangeRegistry = appRegistry.getExchangeRegistry();
- _exchangeFactory = ApplicationRegistry.getInstance().getExchangeFactory();
- _messageStore = ApplicationRegistry.getInstance().getMessageStore();
+
+ _virtualHostMBean = virtualHostMBean;
+ VirtualHost virtualHost = virtualHostMBean.getVirtualHost();
+
+
+
+
+ _queueRegistry = virtualHost.getQueueRegistry();
+ _exchangeRegistry = virtualHost.getExchangeRegistry();
+ _messageStore = virtualHost.getMessageStore();
+ _exchangeFactory = virtualHost.getExchangeFactory();
}
public String getObjectInstanceName()
{
- return this.getClass().getName();
+ return _virtualHostMBean.getVirtualHost().getName();
}
/**
@@ -81,10 +91,10 @@ public class AMQBrokerManagerMBean extends AMQManagedObject implements ManagedBr
{
synchronized (_exchangeRegistry)
{
- Exchange exchange = _exchangeRegistry.getExchange(exchangeName);
+ Exchange exchange = _exchangeRegistry.getExchange(new AMQShortString(exchangeName));
if (exchange == null)
{
- exchange = _exchangeFactory.createExchange(exchangeName, type, durable, autoDelete, 0);
+ exchange = _exchangeFactory.createExchange(new AMQShortString(exchangeName), new AMQShortString(type), durable, autoDelete, 0);
_exchangeRegistry.registerExchange(exchange);
}
else
@@ -114,7 +124,7 @@ public class AMQBrokerManagerMBean extends AMQManagedObject implements ManagedBr
// when there are no bindings.
try
{
- _exchangeRegistry.unregisterExchange(exchangeName, false);
+ _exchangeRegistry.unregisterExchange(new AMQShortString(exchangeName), false);
}
catch (AMQException ex)
{
@@ -135,7 +145,7 @@ public class AMQBrokerManagerMBean extends AMQManagedObject implements ManagedBr
public void createNewQueue(String queueName, boolean durable, String owner, boolean autoDelete)
throws JMException
{
- AMQQueue queue = _queueRegistry.getQueue(queueName);
+ AMQQueue queue = _queueRegistry.getQueue(new AMQShortString(queueName));
if (queue != null)
{
throw new JMException("The queue \"" + queueName + "\" already exists.");
@@ -143,7 +153,7 @@ public class AMQBrokerManagerMBean extends AMQManagedObject implements ManagedBr
try
{
- queue = new AMQQueue(queueName, durable, owner, autoDelete, _queueRegistry);
+ queue = new AMQQueue(new AMQShortString(queueName), durable, new AMQShortString(owner), autoDelete, getVirtualHost());
if (queue.isDurable() && !queue.isAutoDelete())
{
_messageStore.createQueue(queue);
@@ -156,6 +166,11 @@ public class AMQBrokerManagerMBean extends AMQManagedObject implements ManagedBr
}
}
+ private VirtualHost getVirtualHost()
+ {
+ return _virtualHostMBean.getVirtualHost();
+ }
+
/**
* Deletes the queue from queue registry and persistant storage.
*
@@ -164,7 +179,7 @@ public class AMQBrokerManagerMBean extends AMQManagedObject implements ManagedBr
*/
public void deleteQueue(String queueName) throws JMException
{
- AMQQueue queue = _queueRegistry.getQueue(queueName);
+ AMQQueue queue = _queueRegistry.getQueue(new AMQShortString(queueName));
if (queue == null)
{
throw new JMException("The Queue " + queueName + " is not a registerd queue.");
@@ -173,7 +188,7 @@ public class AMQBrokerManagerMBean extends AMQManagedObject implements ManagedBr
try
{
queue.delete();
- _messageStore.removeQueue(queueName);
+ _messageStore.removeQueue(new AMQShortString(queueName));
}
catch (AMQException ex)
@@ -182,11 +197,14 @@ public class AMQBrokerManagerMBean extends AMQManagedObject implements ManagedBr
}
}
- public ObjectName getObjectName() throws MalformedObjectNameException
+ public ManagedObject getParentObject()
{
- StringBuffer objectName = new StringBuffer(ManagedObject.DOMAIN);
- objectName.append(":type=").append(getType());
+ return _virtualHostMBean;
+ }
- return new ObjectName(objectName.toString());
+ // This will have a single instance for a virtual host, so not having the name property in the ObjectName
+ public ObjectName getObjectName() throws MalformedObjectNameException
+ {
+ return getObjectNameForSingleInstanceMBean();
}
} // End of MBean class
diff --git a/java/broker/src/main/java/org/apache/qpid/server/AMQChannel.java b/java/broker/src/main/java/org/apache/qpid/server/AMQChannel.java
index b0ef08d0a5..245e762fa4 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/AMQChannel.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/AMQChannel.java
@@ -27,7 +27,7 @@ import org.apache.log4j.Logger;
import org.apache.mina.common.ByteBuffer;
import org.apache.qpid.AMQException;
import org.apache.qpid.framing.AMQDataBlock;
-import org.apache.qpid.framing.Content;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.framing.Content;
import org.apache.qpid.framing.FieldTable;
import org.apache.qpid.framing.MessageAppendBody;
@@ -43,14 +43,21 @@ import org.apache.qpid.server.ack.UnacknowledgedMessage;
import org.apache.qpid.server.ack.UnacknowledgedMessageMap;
import org.apache.qpid.server.ack.UnacknowledgedMessageMapImpl;
import org.apache.qpid.server.exchange.MessageRouter;
+import org.apache.qpid.server.exchange.NoRouteException;
import org.apache.qpid.server.protocol.AMQProtocolSession;
import org.apache.qpid.server.queue.AMQMessage;
import org.apache.qpid.server.queue.AMQQueue;
-import org.apache.qpid.server.queue.NoConsumersException;
+import org.apache.qpid.server.queue.AMQReference;
+import org.apache.qpid.server.queue.MessageHandleFactory;
import org.apache.qpid.server.store.MessageStore;
-import org.apache.qpid.server.txn.TxnBuffer;
-import org.apache.qpid.server.txn.TxnOp;
+import org.apache.qpid.server.store.StoreContext;
+import org.apache.qpid.server.txn.LocalTransactionalContext;
+import org.apache.qpid.server.txn.NonTransactionalContext;
+import org.apache.qpid.server.txn.TransactionalContext;
+import org.apache.qpid.server.virtualhost.VirtualHost;
+import org.apache.mina.common.ByteBuffer;
+import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
@@ -59,6 +66,7 @@ import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.Set;
+import java.util.HashMap;
import java.util.HashSet;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
@@ -71,7 +79,7 @@ public class AMQChannel
private final int _channelId;
- private boolean _transactional;
+ //private boolean _transactional;
private long _prefetch_HighWaterMark;
@@ -81,6 +89,8 @@ public class AMQChannel
private ResponseManager _responseManager;
private AMQProtocolSession _session;
+ private long _prefetchSize;
+
/**
* The delivery tag is unique per channel. This is pre-incremented before putting into the deliver frame so that
* value of this represents the <b>last</b> tag sent out
@@ -102,30 +112,33 @@ public class AMQChannel
/**
* The set of open references on this channel.
*/
- private Map<String, Reference> _references = new LinkedHashMap();
+ private Map<String, AMQReference> _references = new LinkedHashMap();
/**
* Maps from consumer tag to queue instance. Allows us to unsubscribe from a queue.
*/
- private final Map<String, AMQQueue> _consumerTag2QueueMap = new TreeMap<String, AMQQueue>();
+ private final Map<AMQShortString, AMQQueue> _consumerTag2QueueMap = new HashMap<AMQShortString, AMQQueue>();
private final MessageStore _messageStore;
- private final Object _unacknowledgedMessageMapLock = new Object();
-
- private Map<Long, UnacknowledgedMessage> _unacknowledgedMessageMap = new LinkedHashMap<Long, UnacknowledgedMessage>(DEFAULT_PREFETCH);
-
- private long _lastDeliveryTag;
+ private UnacknowledgedMessageMap _unacknowledgedMessageMap = new UnacknowledgedMessageMapImpl(DEFAULT_PREFETCH);
private final AtomicBoolean _suspended = new AtomicBoolean(false);
private final MessageRouter _exchanges;
- private final TxnBuffer _txnBuffer;
+ private TransactionalContext _txnContext;
+
+ /**
+ * A context used by the message store enabling it to track context for a given channel even across
+ * thread boundaries
+ */
+ private final StoreContext _storeContext = new StoreContext();
+
+ private final List<RequiredDeliveryException> _returnMessages = new LinkedList<RequiredDeliveryException>();
- private TxAck ackOp;
+ private MessageHandleFactory _messageHandleFactory = new MessageHandleFactory();
- private final List<AMQDataBlock> _returns = new LinkedList<AMQDataBlock>();
private Set<Long> _browsedAcks = new HashSet<Long>();
// XXX: clean up arguments
@@ -139,22 +152,29 @@ public class AMQChannel
_exchanges = exchanges;
_requestManager = new RequestManager(_session.getConnectionId(), channelId, _session, true);
_responseManager = new ResponseManager(_session.getConnectionId(), channelId, methodListener, _session, true);
- _txnBuffer = new TxnBuffer(_messageStore);
+ // by default the session is non-transactional
+ _txnContext = new NonTransactionalContext(_messageStore, _storeContext, this, _returnMessages, _browsedAcks);
}
- public int getChannelId()
+ /**
+ * Sets this channel to be part of a local transaction
+ */
+ public void setLocalTransactional()
{
- return _channelId;
+ _txnContext = new LocalTransactionalContext(_messageStore, _storeContext, _returnMessages);
}
public boolean isTransactional()
{
- return _transactional;
+ // this does not look great but there should only be one "non-transactional"
+ // transactional context, while there could be several transactional ones in
+ // theory
+ return !(_txnContext instanceof NonTransactionalContext);
}
- public void setTransactional(boolean transactional)
+ public int getChannelId()
{
- _transactional = transactional;
+ return _channelId;
}
public long getPrefetchCount()
@@ -167,6 +187,17 @@ public class AMQChannel
_prefetch_HighWaterMark = prefetchCount;
}
+ public long getPrefetchSize()
+ {
+ return _prefetchSize;
+ }
+
+
+ public void setPrefetchSize(long prefetchSize)
+ {
+ _prefetchSize = prefetchSize;
+ }
+
public long getPrefetchLowMarkCount()
{
return _prefetch_LowWaterMark;
@@ -193,80 +224,165 @@ public class AMQChannel
AMQMessage message;
switch (body.getContentType()) {
case INLINE_T:
- message = new AMQMessage(_messageStore, transferBody,
- Collections.singletonList(body.getContent()));
+ message = new AMQMessage(_messageStore, transferBody, Collections.singletonList(body.getContent()), _txnContext);
message.setPublisher(publisher);
- route(message);
+ routeCurrentMessage(message);
+ message.routingComplete(_messageStore, _storeContext, _messageHandleFactory);
break;
case REF_T:
- Reference ref = getReference(body.getContentAsByteArray());
- message = new AMQMessage(_messageStore, transferBody, ref.contents);
+ AMQReference ref = getReference(body.getContentAsByteArray());
+ message = new AMQMessage(_messageStore, transferBody, ref.getContentList(), _txnContext);
message.setPublisher(publisher);
- ref.messages.add(message);
+ ref.addRefTransferBody(message);
break;
}
}
- private static String key(byte[] id) {
+ private static String key(byte[] id)
+ {
return new String(id);
}
- private Reference getReference(byte[] id) {
+ private AMQReference getReference(byte[] id)
+ {
String key = key(id);
- Reference ref = _references.get(key);
- if (ref == null) {
+ AMQReference ref = _references.get(key);
+ if (ref == null)
+ {
throw new IllegalArgumentException(key);
}
return ref;
}
- private Reference createReference(byte[] id) {
+ private AMQReference createReference(byte[] id)
+ {
String key = key(id);
- if (_references.containsKey(key)) {
+ if (_references.containsKey(key))
+ {
throw new IllegalArgumentException(key);
}
- Reference ref = new Reference();
+ AMQReference ref = new AMQReference(id);
_references.put(key, ref);
return ref;
}
- private Reference removeReference(byte[] id) {
+ private AMQReference removeReference(byte[] id)
+ {
String key = key(id);
- Reference ref = _references.remove(key);
- if (ref == null) {
+ AMQReference ref = _references.remove(key);
+ if (ref == null)
+ {
throw new IllegalArgumentException(key);
}
return ref;
}
- public void addMessageOpen(MessageOpenBody open) {
+ public void addMessageOpen(MessageOpenBody open)
+ {
createReference(open.reference);
}
- public void addMessageAppend(MessageAppendBody append) {
- Reference ref = getReference(append.reference);
- ref.contents.add(ByteBuffer.wrap(append.bytes));
+ public void addMessageAppend(MessageAppendBody append)
+ {
+ AMQReference ref = getReference(append.reference);
+ ref.appendContent(ByteBuffer.wrap(append.bytes));
+ }
+
+ public void addMessageClose(MessageCloseBody close) throws AMQException
+ {
+ AMQReference ref = removeReference(close.reference);
+ for (AMQMessage msg : ref.getMessageList())
+ {
+ routeCurrentMessage(msg);
+ msg.routingComplete(_messageStore, _storeContext, _messageHandleFactory);
+ }
}
- public void addMessageClose(MessageCloseBody close) throws AMQException {
- Reference ref = removeReference(close.reference);
- for (AMQMessage msg : ref.messages) {
- route(msg);
+ protected void routeCurrentMessage(AMQMessage msg) throws AMQException
+ {
+ try
+ {
+ _exchanges.routeContent(msg);
+ }
+ catch (NoRouteException e)
+ {
+ _returnMessages.add(e);
}
}
+//
+// public void deliver(AMQMessage msg, AMQShortString destination, final long deliveryTag)
+// {
+// deliver(msg, destination, new AMQMethodListener()
+// {
+// public boolean methodReceived(AMQMethodEvent evt) throws AMQException
+// {
+// AMQMethodBody method = evt.getMethod();
+// if (_log.isDebugEnabled())
+// {
+// _log.debug(method + " received on channel " + _channelId);
+// }
+// // XXX: multiple?
+// if (method instanceof MessageOkBody)
+// {
+// acknowledgeMessage(deliveryTag, false);
+// return true;
+// }
+// else
+// {
+// // TODO: implement reject
+// return false;
+// }
+// }
+// public void error(Exception e) {}
+// });
+// }
- public void deliver(AMQMessage msg, String destination, final long deliveryTag) {
- deliver(msg, destination, new AMQMethodListener() {
- public boolean methodReceived(AMQMethodEvent evt) throws AMQException {
+ public void deliver(AMQMessage msg, AMQShortString destination, final long deliveryTag)
+ {
+ // Do we need to refactor the content for a different frame size?
+ long maxFrameSize = _session.getFrameMax();
+ Iterable<ByteBuffer> contentItr = msg.getContents();
+ if (msg.getSize() > maxFrameSize)
+ {
+ Iterator<ByteBuffer> cItr = contentItr.iterator();
+ if (cItr.next().limit() > maxFrameSize) // First chunk should equal incoming frame size
+ {
+ // TODO - Refactor the chunks for smaller outbound frame size
+ throw new Error("XXX TODO - need to refactor content chunks here");
+ // deliverRef(msg, destination, deliveryTag);
+ }
+ else
+ {
+ // Use ref content as is - no need to refactor
+ deliverRef(msg, destination, deliveryTag);
+ }
+ }
+ else
+ {
+ // Concatenate - all incoming chunks will fit into single outbound frame
+ deliverInline(msg, destination, deliveryTag);
+ }
+ }
+
+ public void deliverInline(AMQMessage msg, AMQShortString destination, final long deliveryTag)
+ {
+ deliverInline(msg, destination, new AMQMethodListener()
+ {
+ public boolean methodReceived(AMQMethodEvent evt) throws AMQException
+ {
AMQMethodBody method = evt.getMethod();
- if (_log.isDebugEnabled()) {
+ if (_log.isDebugEnabled())
+ {
_log.debug(method + " received on channel " + _channelId);
}
// XXX: multiple?
- if (method instanceof MessageOkBody) {
+ if (method instanceof MessageOkBody)
+ {
acknowledgeMessage(deliveryTag, false);
return true;
- } else {
+ }
+ else
+ {
// TODO: implement reject
return false;
}
@@ -275,70 +391,127 @@ public class AMQChannel
});
}
- public void deliver(AMQMessage msg, String destination, AMQMethodListener listener) {
- // XXX: should reframe if necessary to conform to max frame size
+ public void deliverInline(AMQMessage msg, AMQShortString destination, AMQMethodListener listener)
+ {
MessageTransferBody mtb = msg.getTransferBody().copy();
mtb.destination = destination;
ByteBuffer buf = ByteBuffer.allocate((int)msg.getBodySize());
- for (ByteBuffer bb : msg.getContents()) {
+ for (ByteBuffer bb : msg.getContents())
+ {
buf.put(bb);
}
buf.flip();
mtb.body = new Content(Content.TypeEnum.INLINE_T, buf);
_session.writeRequest(_channelId, mtb, listener);
}
-
- protected void route(AMQMessage msg) throws AMQException
+
+ public void deliverRef(final AMQMessage msg, final AMQShortString destination, final long deliveryTag)
{
- if (_transactional)
- {
- //don't create a transaction unless needed
- if (msg.isPersistent())
- {
- _txnBuffer.containsPersistentChanges();
- }
-
- //A publication will result in the enlisting of several
- //TxnOps. The first is an op that will store the message.
- //Following that (and ordering is important), an op will
- //be added for every queue onto which the message is
- //enqueued. Finally a cleanup op will be added to decrement
- //the reference associated with the routing.
- Store storeOp = new Store(msg);
- _txnBuffer.enlist(storeOp);
- msg.setTxnBuffer(_txnBuffer);
- try
- {
- _exchanges.routeContent(msg);
- _txnBuffer.enlist(new Cleanup(msg));
- }
- catch (RequiredDeliveryException e)
- {
- //Can only be due to the mandatory flag, as no attempt
- //has yet been made to deliver the message. The
- //message will thus not have been delivered to any
- //queue so we can return the message (without killing
- //the transaction) and for efficiency remove the store
- //operation from the buffer.
- _txnBuffer.cancel(storeOp);
- throw e;
- }
- }
- else
+ final byte[] refId = String.valueOf(System.currentTimeMillis()).getBytes();
+ AMQMethodBody openBody = MessageOpenBody.createMethodBody(
+ _session.getProtocolMajorVersion(), // AMQP major version
+ _session.getProtocolMinorVersion(), // AMQP minor version
+ refId);
+ _session.writeRequest(_channelId, openBody, new AMQMethodListener()
{
- try
- {
- _exchanges.routeContent(msg);
- //following check implements the functionality
- //required by the 'immediate' flag:
- msg.checkDeliveredToConsumer();
- }
- finally
+ public boolean methodReceived(AMQMethodEvent evt) throws AMQException
{
- msg.decrementReference();
+ AMQMethodBody method = evt.getMethod();
+ if (_log.isDebugEnabled())
+ {
+ _log.debug(method + " received on channel " + _channelId);
+ }
+ if (method instanceof MessageOkBody)
+ {
+ acknowledgeMessage(deliveryTag, false);
+ deliverRef(refId, msg, destination, _session.getStateManager());
+ return true;
+ }
+ else
+ {
+ // TODO: implement reject
+ return false;
+ }
}
- }
+ public void error(Exception e) {}
+ });
}
+
+ public void deliverRef(byte[] refId, AMQMessage msg, AMQShortString destination, AMQMethodListener listener)
+ {
+ MessageTransferBody mtb = msg.getTransferBody().copy();
+ mtb.destination = destination;
+ mtb.body = new Content(Content.TypeEnum.REF_T, refId);
+ _session.writeRequest(_channelId, mtb, listener);
+ for (ByteBuffer bb : msg.getContents())
+ {
+ ByteBuffer dup = bb.duplicate();
+ byte[] ba = new byte[dup.limit()];
+ dup.get(ba);
+ AMQMethodBody appendBody = MessageAppendBody.createMethodBody(
+ _session.getProtocolMajorVersion(), // AMQP major version
+ _session.getProtocolMinorVersion(), // AMQP minor version
+ ba,
+ refId);
+ _session.writeRequest(_channelId, appendBody, listener);
+ }
+ AMQMethodBody closeBody = MessageCloseBody.createMethodBody(
+ _session.getProtocolMajorVersion(), // AMQP major version
+ _session.getProtocolMinorVersion(), // AMQP minor version
+ refId);
+ }
+
+// protected void route(AMQMessage msg) throws AMQException
+// {
+// if (isTransactional())
+// {
+// //don't create a transaction unless needed
+// if (msg.isPersistent())
+// {
+// // _txnBuffer.containsPersistentChanges();
+// }
+//
+// //A publication will result in the enlisting of several
+// //TxnOps. The first is an op that will store the message.
+// //Following that (and ordering is important), an op will
+// //be added for every queue onto which the message is
+// //enqueued. Finally a cleanup op will be added to decrement
+// //the reference associated with the routing.
+// // Store storeOp = new Store(msg);
+// // _txnBuffer.enlist(storeOp);
+// // msg.setTxnBuffer(_txnBuffer);
+// try
+// {
+// _exchanges.routeContent(msg);
+// // _txnBuffer.enlist(new Cleanup(msg));
+// }
+// catch (RequiredDeliveryException e)
+// {
+// //Can only be due to the mandatory flag, as no attempt
+// //has yet been made to deliver the message. The
+// //message will thus not have been delivered to any
+// //queue so we can return the message (without killing
+// //the transaction) and for efficiency remove the store
+// //operation from the buffer.
+// // _txnBuffer.cancel(storeOp);
+// throw e;
+// }
+// }
+// else
+// {
+// try
+// {
+// _exchanges.routeContent(msg);
+// //following check implements the functionality
+// //required by the 'immediate' flag:
+// msg.checkDeliveredToConsumer();
+// }
+// finally
+// {
+// msg.decrementReference(_storeContext);
+// }
+// }
+// }
public RequestManager getRequestManager()
{
@@ -369,17 +542,19 @@ public class AMQChannel
* @param queue the queue to subscribe to
* @param session the protocol session of the subscriber
* @param noLocal
+ * @param exclusive
* @return the consumer tag. This is returned to the subscriber and used in
* subsequent unsubscribe requests
* @throws ConsumerTagNotUniqueException if the tag is not unique
* @throws AMQException if something goes wrong
*/
- public String subscribeToQueue(String tag, AMQQueue queue, AMQProtocolSession session, boolean acks,
- FieldTable filters, boolean noLocal, boolean exclusive) throws AMQException, ConsumerTagNotUniqueException
+ public AMQShortString subscribeToQueue(AMQShortString tag, AMQQueue queue,
+ AMQProtocolSession session, boolean acks, FieldTable filters,
+ boolean noLocal, boolean exclusive) throws AMQException, ConsumerTagNotUniqueException
{
if (tag == null)
{
- tag = "sgen_" + getNextConsumerTag();
+ tag = new AMQShortString("sgen_" + getNextConsumerTag());
}
if (_consumerTag2QueueMap.containsKey(tag))
{
@@ -392,7 +567,7 @@ public class AMQChannel
}
- public void unsubscribeConsumer(AMQProtocolSession session, String consumerTag) throws AMQException
+ public void unsubscribeConsumer(AMQProtocolSession session, AMQShortString consumerTag) throws AMQException
{
AMQQueue q = _consumerTag2QueueMap.remove(consumerTag);
if (q != null)
@@ -408,21 +583,16 @@ public class AMQChannel
*/
public void close(AMQProtocolSession session) throws AMQException
{
- if (_transactional)
- {
- synchronized(_txnBuffer)
- {
- _txnBuffer.rollback();//releases messages
- }
- }
+ _txnContext.rollback();
unsubscribeAllConsumers(session);
requeue();
+ _txnContext.commit();
}
private void unsubscribeAllConsumers(AMQProtocolSession session) throws AMQException
{
_log.info("Unsubscribing all consumers on channel " + toString());
- for (Map.Entry<String, AMQQueue> me : _consumerTag2QueueMap.entrySet())
+ for (Map.Entry<AMQShortString, AMQQueue> me : _consumerTag2QueueMap.entrySet())
{
me.getValue().unregisterProtocolSession(session, _channelId, me.getKey());
}
@@ -432,16 +602,16 @@ public class AMQChannel
/**
* Add a message to the channel-based list of unacknowledged messages
*
- * @param message
- * @param deliveryTag
- * @param queue
+ * @param message the message that was delivered
+ * @param deliveryTag the delivery tag used when delivering the message (see protocol spec for description of
+ * the delivery tag)
+ * @param queue the queue from which the message was delivered
*/
- public void addUnacknowledgedMessage(AMQMessage message, long deliveryTag, String consumerTag, AMQQueue queue)
+ public void addUnacknowledgedMessage(AMQMessage message, long deliveryTag, AMQShortString consumerTag, AMQQueue queue)
{
- synchronized(_unacknowledgedMessageMapLock)
+ synchronized (_unacknowledgedMessageMap.getLock())
{
- _unacknowledgedMessageMap.put(deliveryTag, new UnacknowledgedMessage(queue, message, consumerTag, deliveryTag));
- _lastDeliveryTag = deliveryTag;
+ _unacknowledgedMessageMap.add(deliveryTag, new UnacknowledgedMessage(queue, message, consumerTag, deliveryTag));
checkSuspension();
}
}
@@ -449,24 +619,19 @@ public class AMQChannel
/**
* Called to attempt re-enqueue all outstanding unacknowledged messages on the channel.
* May result in delivery to this same channel or to other subscribers.
+ *
+ * @throws org.apache.qpid.AMQException if the requeue fails
*/
public void requeue() throws AMQException
{
// we must create a new map since all the messages will get a new delivery tag when they are redelivered
- Map<Long, UnacknowledgedMessage> currentList;
- synchronized(_unacknowledgedMessageMapLock)
- {
- currentList = _unacknowledgedMessageMap;
- _unacknowledgedMessageMap = new LinkedHashMap<Long, UnacknowledgedMessage>(DEFAULT_PREFETCH);
- }
+ Collection<UnacknowledgedMessage> messagesToBeDelivered = _unacknowledgedMessageMap.cancelAllMessages();
- for (UnacknowledgedMessage unacked : currentList.values())
+ for (UnacknowledgedMessage unacked : messagesToBeDelivered)
{
if (unacked.queue != null)
{
- unacked.message.setTxnBuffer(null);
-
- unacked.queue.deliver(unacked.message);
+ _txnContext.deliver(unacked.message, unacked.queue);
}
}
}
@@ -474,53 +639,87 @@ public class AMQChannel
/**
* Called to resend all outstanding unacknowledged messages to this same channel.
*/
- public void resend(AMQProtocolSession session)
- {
- //messages go to this channel
- synchronized(_unacknowledgedMessageMapLock)
- {
- for (Map.Entry<Long, UnacknowledgedMessage> entry : _unacknowledgedMessageMap.entrySet())
- {
- long deliveryTag = entry.getKey();
- String consumerTag = entry.getValue().consumerTag;
- AMQMessage msg = entry.getValue().message;
- msg.setRedelivered(true);
- deliver(msg, consumerTag, deliveryTag);
- }
- }
- }
+ public void resend(final AMQProtocolSession session, final boolean requeue) throws AMQException
+ {
+ throw new Error("XXX");
+// final List<UnacknowledgedMessage> msgToRequeue = new LinkedList<UnacknowledgedMessage>();
+//
+// _unacknowledgedMessageMap.visit(new UnacknowledgedMessageMap.Visitor()
+// {
+// public boolean callback(UnacknowledgedMessage message) throws AMQException
+// {
+// long deliveryTag = message.deliveryTag;
+// AMQShortString consumerTag = message.consumerTag;
+// AMQMessage msg = message.message;
+// msg.setRedelivered(true);
+// // working
+// // deliver(msg, consumerTag, deliveryTag);
+// // trunk
+// if((consumerTag != null) && _consumerTag2QueueMap.containsKey(consumerTag))
+// {
+// msg.writeDeliver(session, _channelId, deliveryTag, consumerTag);
+// }
+// else
+// {
+// // Message has no consumer tag, so was "delivered" to a GET
+// // or consumer no longer registered
+// // cannot resend, so re-queue.
+// if (message.queue != null && (consumerTag == null || requeue))
+// {
+// msgToRequeue.add(message);
+// }
+// }
+// // false means continue processing
+// return false;
+// }
+//
+// public void visitComplete()
+// {
+// }
+// });
+//
+// for(UnacknowledgedMessage message : msgToRequeue)
+// {
+// _txnContext.deliver(message.message, message.queue);
+// _unacknowledgedMessageMap.remove(message.deliveryTag);
+// }
+ }
/**
* Callback indicating that a queue has been deleted. We must update the structure of unacknowledged
* messages to remove the queue reference and also decrement any message reference counts, without
- * actually removing the item sine we may get an ack for a delivery tag that was generated from the
+ * actually removing the item since we may get an ack for a delivery tag that was generated from the
* deleted queue.
*
- * @param queue
+ * @param queue the queue that has been deleted
+ * @throws org.apache.qpid.AMQException if there is an error processing the unacked messages
*/
- public void queueDeleted(AMQQueue queue)
+ public void queueDeleted(final AMQQueue queue) throws AMQException
{
- synchronized(_unacknowledgedMessageMapLock)
+ _unacknowledgedMessageMap.visit(new UnacknowledgedMessageMap.Visitor()
{
- for (Map.Entry<Long, UnacknowledgedMessage> unacked : _unacknowledgedMessageMap.entrySet())
+ public boolean callback(UnacknowledgedMessage message) throws AMQException
{
- final UnacknowledgedMessage unackedMsg = unacked.getValue();
- // we can compare the reference safely in this case
- if (unackedMsg.queue == queue)
+ if (message.queue == queue)
{
- unackedMsg.queue = null;
try
{
- unackedMsg.message.decrementReference();
+ message.discard(_storeContext);
+ message.queue = null;
}
catch (AMQException e)
{
- _log.error("Error decrementing ref count on message " + unackedMsg.message.getMessageId() + ": " +
+ _log.error("Error decrementing ref count on message " + message.message.getMessageId() + ": " +
e, e);
}
}
+ return false;
}
- }
+
+ public void visitComplete()
+ {
+ }
+ });
}
/**
@@ -533,151 +732,11 @@ public class AMQChannel
*/
public void acknowledgeMessage(long deliveryTag, boolean multiple) throws AMQException
{
- if (_transactional)
- {
- //check that the tag exists to give early failure
- if (!multiple || deliveryTag > 0)
- {
- checkAck(deliveryTag);
- }
- //we use a single txn op for all acks and update this op
- //as new acks come in. If this is the first ack in the txn
- //we will need to create and enlist the op.
- if (ackOp == null)
- {
- ackOp = new TxAck(new AckMap());
- _txnBuffer.enlist(ackOp);
- }
- //update the op to include this ack request
- if (multiple && deliveryTag == 0)
- {
- synchronized(_unacknowledgedMessageMapLock)
- {
- //if have signalled to ack all, that refers only
- //to all at this time
- ackOp.update(_lastDeliveryTag, multiple);
- }
- }
- else
- {
- ackOp.update(deliveryTag, multiple);
- }
- }
- else
+ synchronized (_unacknowledgedMessageMap.getLock())
{
- handleAcknowledgement(deliveryTag, multiple);
- }
- }
-
- private void checkAck(long deliveryTag) throws AMQException
- {
- synchronized(_unacknowledgedMessageMapLock)
- {
- if (!_unacknowledgedMessageMap.containsKey(deliveryTag))
- {
- throw new AMQException("Ack with delivery tag " + deliveryTag + " not known for channel");
- }
- }
- }
-
- private void handleAcknowledgement(long deliveryTag, boolean multiple) throws AMQException
- {
- if (_log.isDebugEnabled())
- {
- _log.debug("Handling acknowledgement for channel " + _channelId + " with delivery tag " + deliveryTag +
- " and multiple " + multiple);
- }
- if (multiple)
- {
- LinkedList<UnacknowledgedMessage> acked = new LinkedList<UnacknowledgedMessage>();
- synchronized(_unacknowledgedMessageMapLock)
- {
- if (deliveryTag == 0)
- {
- //Spec 2.1.6.11 ... If the multiple field is 1, and the delivery tag is zero, tells the server to acknowledge all outstanding mesages.
- _log.trace("Multiple ack on delivery tag 0. ACKing all messages. Current count:" + _unacknowledgedMessageMap.size());
- acked = new LinkedList<UnacknowledgedMessage>(_unacknowledgedMessageMap.values());
- _unacknowledgedMessageMap.clear();
- }
- else
- {
- if (!_unacknowledgedMessageMap.containsKey(deliveryTag))
- {
- throw new AMQException("Multiple ack on delivery tag " + deliveryTag + " not known for channel");
- }
- Iterator<Map.Entry<Long, UnacknowledgedMessage>> i = _unacknowledgedMessageMap.entrySet().iterator();
-
- while (i.hasNext())
- {
-
- Map.Entry<Long, UnacknowledgedMessage> unacked = i.next();
-
- if (unacked.getKey() > deliveryTag)
- {
- //This should not occur now.
- throw new AMQException("UnacknowledgedMessageMap is out of order:" + unacked.getKey() + " When deliveryTag is:" + deliveryTag + "ES:" + _unacknowledgedMessageMap.entrySet().toString());
- }
-
- i.remove();
-
- acked.add(unacked.getValue());
- if (unacked.getKey() == deliveryTag)
- {
- break;
- }
- }
- }
- }// synchronized
-
- if (_log.isTraceEnabled())
- {
- _log.trace("Received multiple ack for delivery tag " + deliveryTag + ". Removing " +
- acked.size() + " items.");
- }
-
- for (UnacknowledgedMessage msg : acked)
- {
- if (!_browsedAcks.contains(deliveryTag))
- {
- msg.discard();
- }
- else
- {
- _browsedAcks.remove(deliveryTag);
- }
- }
-
- }
- else
- {
- UnacknowledgedMessage msg;
- synchronized(_unacknowledgedMessageMapLock)
- {
- msg = _unacknowledgedMessageMap.remove(deliveryTag);
- }
-
- if (msg == null)
- {
- _log.trace("Single ack on delivery tag " + deliveryTag + " not known for channel:" + _channelId);
- throw new AMQException("Single ack on delivery tag " + deliveryTag + " not known for channel:" + _channelId);
- }
-
- if (!_browsedAcks.contains(deliveryTag))
- {
- msg.discard();
- }
- else
- {
- _browsedAcks.remove(deliveryTag);
- }
-
- if (_log.isTraceEnabled())
- {
- _log.trace("Received non-multiple ack for messaging with delivery tag " + deliveryTag);
- }
+ _unacknowledgedMessageMap.acknowledgeMessage(deliveryTag, multiple, _txnContext);
+ checkSuspension();
}
-
- checkSuspension();
}
/**
@@ -685,19 +744,24 @@ public class AMQChannel
*
* @return the map of unacknowledged messages
*/
- public Map<Long, UnacknowledgedMessage> getUnacknowledgedMessageMap()
+ public UnacknowledgedMessageMap getUnacknowledgedMessageMap()
{
return _unacknowledgedMessageMap;
}
+ public void addUnacknowledgedBrowsedMessage(AMQMessage msg, long deliveryTag, AMQShortString consumerTag, AMQQueue queue)
+ {
+ _browsedAcks.add(deliveryTag);
+ addUnacknowledgedMessage(msg, deliveryTag, consumerTag, queue);
+ }
+
private void checkSuspension()
{
boolean suspend;
- //noinspection SynchronizeOnNonFinalField
- synchronized(_unacknowledgedMessageMapLock)
- {
- suspend = _unacknowledgedMessageMap.size() >= _prefetch_HighWaterMark;
- }
+
+ suspend = ((_prefetch_HighWaterMark != 0) && _unacknowledgedMessageMap.size() >= _prefetch_HighWaterMark)
+ || ((_prefetchSize != 0) && _prefetchSize < _unacknowledgedMessageMap.getUnacknowledgeBytes());
+
setSuspended(suspend);
}
@@ -707,11 +771,8 @@ public class AMQChannel
if (isSuspended && !suspended)
{
- synchronized(_unacknowledgedMessageMapLock)
- {
- // Continue being suspended if we are above the _prefetch_LowWaterMark
- suspended = _unacknowledgedMessageMap.size() > _prefetch_LowWaterMark;
- }
+ // Continue being suspended if we are above the _prefetch_LowWaterMark
+ suspended = _unacknowledgedMessageMap.size() > _prefetch_LowWaterMark;
}
boolean wasSuspended = _suspended.getAndSet(suspended);
@@ -740,33 +801,22 @@ public class AMQChannel
public void commit() throws AMQException
{
- if (ackOp != null)
+ if (!isTransactional())
{
- ackOp.consolidate();
- if (ackOp.checkPersistent())
- {
- _txnBuffer.containsPersistentChanges();
- }
- ackOp = null;//already enlisted, after commit will reset regardless of outcome
+ throw new AMQException("Fatal error: commit called on non-transactional channel");
}
-
- _txnBuffer.commit();
- //TODO: may need to return 'immediate' messages at this point
+ _txnContext.commit();
}
public void rollback() throws AMQException
{
- //need to protect rollback and close from each other...
- synchronized(_txnBuffer)
- {
- _txnBuffer.rollback();
- }
+ _txnContext.rollback();
}
public String toString()
{
StringBuilder sb = new StringBuilder(30);
- sb.append("Channel: id ").append(_channelId).append(", transaction mode: ").append(_transactional);
+ sb.append("Channel: id ").append(_channelId).append(", transaction mode: ").append(isTransactional());
sb.append(", prefetch marks: ").append(_prefetch_LowWaterMark);
sb.append("/").append(_prefetch_HighWaterMark);
return sb.toString();
@@ -782,129 +832,46 @@ public class AMQChannel
return _defaultQueue;
}
- public void processReturns(AMQProtocolSession session)
- {
- for (AMQDataBlock block : _returns)
- {
- session.writeFrame(block);
- }
- _returns.clear();
- }
-
- public void addUnacknowledgedBrowsedMessage(AMQMessage msg, long deliveryTag, String consumerTag, AMQQueue queue)
+ public StoreContext getStoreContext()
{
- _browsedAcks.add(deliveryTag);
- addUnacknowledgedMessage(msg, deliveryTag, consumerTag, queue);
+ return _storeContext;
}
- //we use this wrapper to ensure we are always using the correct
- //map instance (its not final unfortunately)
- private class AckMap implements UnacknowledgedMessageMap
+ public void processReturns(AMQProtocolSession session) throws AMQException
{
- public void collect(long deliveryTag, boolean multiple, List<UnacknowledgedMessage> msgs)
- {
- impl().collect(deliveryTag, multiple, msgs);
- }
-
- public void remove(List<UnacknowledgedMessage> msgs)
+ for (RequiredDeliveryException bouncedMessage : _returnMessages)
{
- impl().remove(msgs);
- }
-
- private UnacknowledgedMessageMap impl()
- {
- return new UnacknowledgedMessageMapImpl(_unacknowledgedMessageMapLock, _unacknowledgedMessageMap);
+ AMQMessage message = bouncedMessage.getAMQMessage();
+ session.writeResponse(_channelId, message.getMessageId(), message.getTransferBody());
+// message.writeReturn(session, _channelId, bouncedMessage.getReplyCode(), new AMQShortString(bouncedMessage.getMessage()));
}
+ _returnMessages.clear();
}
- private class Store implements TxnOp
- {
- //just use this to do a store of the message during the
- //prepare phase. Any enqueueing etc is done by TxnOps enlisted
- //by the queues themselves.
- private final AMQMessage _msg;
-
- Store(AMQMessage msg)
- {
- _msg = msg;
- }
-
- public void prepare() throws AMQException
- {
- _msg.storeMessage();
- //the routers reference can now be released
- _msg.decrementReference();
- }
- public void undoPrepare()
- {
- }
-
- public void commit()
- {
- }
-
- public void rollback()
- {
- }
- }
-
- private class Cleanup implements TxnOp
+ public boolean wouldSuspend(AMQMessage msg)
{
- private final AMQMessage _msg;
-
- Cleanup(AMQMessage msg)
- {
- _msg = msg;
- }
-
- public void prepare() throws AMQException
+ if (isSuspended())
{
+ return true;
}
-
- public void undoPrepare()
- {
- //don't need to do anything here, if the store's txn failed
- //when processing prepare then the message was not stored
- //or enqueued on any queues and can be discarded
- }
-
- public void commit()
+ else
{
- //The routers reference can now be released. This is done
- //here to ensure that it happens after the queues that
- //enqueue it have incremented their counts (which as a
- //memory only operation is done in the commit phase).
- try
- {
- _msg.decrementReference();
- }
- catch (AMQException e)
- {
- _log.error("On commiting transaction, failed to cleanup unused message: " + e, e);
- }
- try
+ boolean willSuspend = ((_prefetch_HighWaterMark != 0) && _unacknowledgedMessageMap.size() + 1 > _prefetch_HighWaterMark);
+ if(!willSuspend)
{
- _msg.checkDeliveredToConsumer();
+ final long unackedSize = _unacknowledgedMessageMap.getUnacknowledgeBytes();
+
+ willSuspend = (_prefetchSize != 0) && (unackedSize != 0) && (_prefetchSize < msg.getSize() + unackedSize);
}
- catch (NoConsumersException e)
+
+
+ if(willSuspend)
{
- //TODO: store this for delivery after the commit-ok
- throw new Error("XXX");
- //_returns.add(e.getReturnMessage(_channelId));
+ setSuspended(true);
}
+ return willSuspend;
}
- public void rollback()
- {
- }
}
-
- private static class Reference {
-
- public List<AMQMessage> messages = new LinkedList();
- public List<ByteBuffer> contents = new LinkedList();
-
- }
-
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/Main.java b/java/broker/src/main/java/org/apache/qpid/server/Main.java
index ffd25de0b4..55009bbf49 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/Main.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/Main.java
@@ -62,7 +62,7 @@ import java.util.StringTokenizer;
* Main entry point for AMQPD.
*
*/
-public class Main implements ProtocolVersionList, Managable
+public class Main implements ProtocolVersionList
{
private static final Logger _logger = Logger.getLogger(Main.class);
@@ -70,7 +70,8 @@ public class Main implements ProtocolVersionList, Managable
private static final String DEFAULT_LOG_CONFIG_FILENAME = "log4j.xml";
- private AMQBrokerManagerMBean _mbean = null;
+
+ private static Main _instance;
protected static class InitException extends Exception
{
@@ -265,7 +266,6 @@ public class Main implements ProtocolVersionList, Managable
}
bind(port, connectorConfig);
- createAndRegisterBrokerMBean();
}
protected void setupVirtualHosts(String configFileParent, String configFilePath) throws ConfigurationException, AMQException, URLSyntaxException
@@ -324,7 +324,7 @@ public class Main implements ProtocolVersionList, Managable
// implementation provided by MINA
if (connectorConfig.enableExecutorPool)
{
- sconfig.setThreadModel(new ReadWriteThreadModel());
+ sconfig.setThreadModel(ReadWriteThreadModel.getInstance());
}
if (connectorConfig.enableNonSSL)
@@ -368,7 +368,7 @@ public class Main implements ProtocolVersionList, Managable
public static void main(String[] args)
{
- new Main(args);
+ _instance = new Main(args);
}
private byte[] parseIP(String address) throws Exception
@@ -430,21 +430,4 @@ public class Main implements ProtocolVersionList, Managable
}
}
- private void createAndRegisterBrokerMBean() throws AMQException
- {
- try
- {
- _mbean = new AMQBrokerManagerMBean();
- _mbean.register();
- }
- catch (JMException ex)
- {
- throw new AMQException("Exception occured in creating AMQBrokerManager MBean");
- }
- }
-
- public ManagedObject getManagedObject()
- {
- return _mbean;
- }
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/RequiredDeliveryException.java b/java/broker/src/main/java/org/apache/qpid/server/RequiredDeliveryException.java
index a1a6a77a93..b85e3603b7 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/RequiredDeliveryException.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/RequiredDeliveryException.java
@@ -7,9 +7,9 @@
* 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
@@ -20,14 +20,9 @@
*/
package org.apache.qpid.server;
-import org.apache.qpid.framing.MessageTransferBody;
-import org.apache.qpid.framing.CompositeAMQDataBlock;
-import org.apache.qpid.framing.AMQFrame;
import org.apache.qpid.AMQException;
import org.apache.qpid.server.queue.AMQMessage;
-import java.util.List;
-
/**
* Signals that a required delivery could not be made. This could be bacuse of
* the immediate flag being set and the queue having no consumers, or the mandatory
@@ -35,48 +30,24 @@ import java.util.List;
*/
public abstract class RequiredDeliveryException extends AMQException
{
- private final String _message;
- private final AMQMessage _payload;
+ private final AMQMessage _amqMessage;
public RequiredDeliveryException(String message, AMQMessage payload)
{
super(message);
- _message = message;
- _payload = payload;
+ _amqMessage = payload;
+ payload.incrementReference();
}
- /* public CompositeAMQDataBlock getReturnMessage(int channel)
+ public AMQMessage getAMQMessage()
{
- // AMQP version change: All generated *Body classes are now version-aware.
- // Shortcut: hardwire version to 0-9 (major=0, minor=9) for now.
- // TODO: Connect the version to that returned by the ProtocolInitiation
- // for this session.
- BasicReturnBody returnBody = new BasicReturnBody((byte)0, (byte)9);
- returnBody.exchange = _transferBody.exchange;
- returnBody.replyCode = getReplyCode();
- returnBody.replyText = _message;
- returnBody.routingKey = _transferBody.routingKey;
-
- AMQFrame[] allFrames = new AMQFrame[2 + _contentBodies.size()];
-
- AMQFrame returnFrame = new AMQFrame();
- returnFrame.bodyFrame = returnBody;
- returnFrame.channel = channel;
-
- allFrames[0] = returnFrame;
- allFrames[1] = ContentHeaderBody.createAMQFrame(channel, _contentHeaderBody);
- for (int i = 2; i < allFrames.length; i++)
- {
- allFrames[i] = ContentBody.createAMQFrame(channel, _contentBodies.get(i - 2));
- }
-
- return new CompositeAMQDataBlock(allFrames);
- }*/
+ return _amqMessage;
+ }
public int getErrorCode()
{
return getReplyCode();
- }
+ }
public abstract int getReplyCode();
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/ack/TxAck.java b/java/broker/src/main/java/org/apache/qpid/server/ack/TxAck.java
index a204e176aa..c0a631080e 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/ack/TxAck.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/ack/TxAck.java
@@ -7,9 +7,9 @@
* 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
@@ -22,13 +22,14 @@ package org.apache.qpid.server.ack;
import org.apache.qpid.AMQException;
import org.apache.qpid.server.txn.TxnOp;
+import org.apache.qpid.server.store.StoreContext;
import java.util.LinkedList;
import java.util.List;
/**
* A TxnOp implementation for handling accumulated acks
- */
+ */
public class TxAck implements TxnOp
{
private final UnacknowledgedMessageMap _map;
@@ -44,14 +45,14 @@ public class TxAck implements TxnOp
public void update(long deliveryTag, boolean multiple)
{
- if(!multiple)
+ if (!multiple)
{
//have acked a single message that is not part of
//the previously acked region so record
//individually
_individual.add(deliveryTag);//_multiple && !multiple
}
- else if(deliveryTag > _deliveryTag)
+ else if (deliveryTag > _deliveryTag)
{
//have simply moved the last acked message on a
//bit
@@ -63,7 +64,7 @@ public class TxAck implements TxnOp
public void consolidate()
{
//lookup all the unacked messages that have been acked in this transaction
- if(_multiple)
+ if (_multiple)
{
//get all the unacked messages for the accumulated
//multiple acks
@@ -71,22 +72,22 @@ public class TxAck implements TxnOp
}
//get any unacked messages for individual acks outside the
//range covered by multiple acks
- for(long tag : _individual)
+ for (long tag : _individual)
{
if(_deliveryTag < tag)
{
- _map.collect(tag, false, _unacked);
+ _map.collect(tag, false, _unacked);
}
}
}
public boolean checkPersistent() throws AMQException
- {
+ {
//if any of the messages in unacked are persistent the txn
//buffer must be marked as persistent:
- for(UnacknowledgedMessage msg : _unacked)
+ for (UnacknowledgedMessage msg : _unacked)
{
- if(msg.message.isPersistent())
+ if (msg.message.isPersistent())
{
return true;
}
@@ -94,34 +95,34 @@ public class TxAck implements TxnOp
return false;
}
- public void prepare() throws AMQException
+ public void prepare(StoreContext storeContext) throws AMQException
{
//make persistent changes, i.e. dequeue and decrementReference
- for(UnacknowledgedMessage msg : _unacked)
+ for (UnacknowledgedMessage msg : _unacked)
{
- msg.discard();
+ msg.discard(storeContext);
}
}
-
+
public void undoPrepare()
{
//decrementReference is annoyingly untransactional (due to
//in memory counter) so if we failed in prepare for full
//txn, this op will have to compensate by fixing the count
- //in memory (persistent changes will be rolled back by store)
- for(UnacknowledgedMessage msg : _unacked)
+ //in memory (persistent changes will be rolled back by store)
+ for (UnacknowledgedMessage msg : _unacked)
{
msg.message.incrementReference();
- }
+ }
}
- public void commit()
+ public void commit(StoreContext storeContext)
{
//remove the unacked messages from the channels map
_map.remove(_unacked);
}
- public void rollback()
+ public void rollback(StoreContext storeContext)
{
}
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/ack/UnacknowledgedMessage.java b/java/broker/src/main/java/org/apache/qpid/server/ack/UnacknowledgedMessage.java
index 0eff5a3cca..ff3c901be5 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/ack/UnacknowledgedMessage.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/ack/UnacknowledgedMessage.java
@@ -7,9 +7,9 @@
* 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
@@ -21,31 +21,34 @@
package org.apache.qpid.server.ack;
import org.apache.qpid.AMQException;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.server.queue.AMQMessage;
import org.apache.qpid.server.queue.AMQQueue;
+import org.apache.qpid.server.store.StoreContext;
public class UnacknowledgedMessage
{
public final AMQMessage message;
- public final String consumerTag;
+ public final AMQShortString consumerTag;
public final long deliveryTag;
public AMQQueue queue;
-
- public UnacknowledgedMessage(AMQQueue queue, AMQMessage message, String consumerTag, long deliveryTag)
+
+ public UnacknowledgedMessage(AMQQueue queue, AMQMessage message, AMQShortString consumerTag, long deliveryTag)
{
this.queue = queue;
this.message = message;
this.consumerTag = consumerTag;
this.deliveryTag = deliveryTag;
+ message.incrementReference();
}
- public void discard() throws AMQException
+ public void discard(StoreContext storeContext) throws AMQException
{
if (queue != null)
{
- message.dequeue(queue);
+ message.dequeue(storeContext, queue);
}
- message.decrementReference();
+ message.decrementReference(storeContext);
}
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/ack/UnacknowledgedMessageMap.java b/java/broker/src/main/java/org/apache/qpid/server/ack/UnacknowledgedMessageMap.java
index b0bbe224e3..7ea22a447f 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/ack/UnacknowledgedMessageMap.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/ack/UnacknowledgedMessageMap.java
@@ -7,9 +7,9 @@
* 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
@@ -20,11 +20,60 @@
*/
package org.apache.qpid.server.ack;
+import org.apache.qpid.AMQException;
+import org.apache.qpid.server.txn.TransactionalContext;
+
+import java.util.Collection;
import java.util.List;
+import java.util.Set;
public interface UnacknowledgedMessageMap
{
- public void collect(long deliveryTag, boolean multiple, List<UnacknowledgedMessage> msgs);
- public void remove(List<UnacknowledgedMessage> msgs);
+ public interface Visitor
+ {
+ /**
+ * @param message the message being iterated over
+ * @return true to stop iteration, false to continue
+ * @throws AMQException
+ */
+ boolean callback(UnacknowledgedMessage message) throws AMQException;
+
+ void visitComplete();
+ }
+
+ void visit(Visitor visitor) throws AMQException;
+
+ Object getLock();
+
+ void add(long deliveryTag, UnacknowledgedMessage message);
+
+ void collect(long deliveryTag, boolean multiple, List<UnacknowledgedMessage> msgs);
+
+ boolean contains(long deliveryTag) throws AMQException;
+
+ void remove(List<UnacknowledgedMessage> msgs);
+
+ UnacknowledgedMessage remove(long deliveryTag);
+
+ void drainTo(Collection<UnacknowledgedMessage> destination, long deliveryTag) throws AMQException;
+
+ Collection<UnacknowledgedMessage> cancelAllMessages();
+
+ void acknowledgeMessage(long deliveryTag, boolean multiple, TransactionalContext txnContext) throws AMQException;
+
+ int size();
+
+ void clear();
+
+ UnacknowledgedMessage get(long deliveryTag);
+
+ /**
+ * Get the set of delivery tags that are outstanding.
+ *
+ * @return a set of delivery tags
+ */
+ Set<Long> getDeliveryTags();
+
+ public long getUnacknowledgeBytes();
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/ack/UnacknowledgedMessageMapImpl.java b/java/broker/src/main/java/org/apache/qpid/server/ack/UnacknowledgedMessageMapImpl.java
index eda3233e56..27b2c50f09 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/ack/UnacknowledgedMessageMapImpl.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/ack/UnacknowledgedMessageMapImpl.java
@@ -7,9 +7,9 @@
* 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
@@ -20,19 +20,38 @@
*/
package org.apache.qpid.server.ack;
-import java.util.List;
-import java.util.Map;
+import org.apache.qpid.server.AMQChannel;
+import org.apache.qpid.server.queue.AMQMessage;
+import org.apache.qpid.server.protocol.AMQProtocolSession;
+import org.apache.qpid.server.txn.TransactionalContext;
+import org.apache.qpid.AMQException;
+import org.apache.qpid.framing.AMQShortString;
+
+import java.util.*;
public class UnacknowledgedMessageMapImpl implements UnacknowledgedMessageMap
{
- private final Object _lock;
+ private final Object _lock = new Object();
+
+ private long _unackedSize;
+
private Map<Long, UnacknowledgedMessage> _map;
- public UnacknowledgedMessageMapImpl(Object lock, Map<Long, UnacknowledgedMessage> map)
+ private long _lastDeliveryTag;
+
+ private final int _prefetchLimit;
+
+ public UnacknowledgedMessageMapImpl(int prefetchLimit)
+ {
+ _prefetchLimit = prefetchLimit;
+ _map = new LinkedHashMap<Long, UnacknowledgedMessage>(prefetchLimit);
+ }
+
+ /*public UnacknowledgedMessageMapImpl(Object lock, Map<Long, UnacknowledgedMessage> map)
{
_lock = lock;
_map = map;
- }
+ } */
public void collect(long deliveryTag, boolean multiple, List<UnacknowledgedMessage> msgs)
{
@@ -47,38 +66,187 @@ public class UnacknowledgedMessageMapImpl implements UnacknowledgedMessageMap
}
+ public boolean contains(long deliveryTag) throws AMQException
+ {
+ synchronized (_lock)
+ {
+ return _map.containsKey(deliveryTag);
+ }
+ }
+
public void remove(List<UnacknowledgedMessage> msgs)
{
- synchronized(_lock)
+ synchronized (_lock)
{
- for(UnacknowledgedMessage msg : msgs)
+ for (UnacknowledgedMessage msg : msgs)
{
- _map.remove(msg.deliveryTag);
- }
+ remove(msg.deliveryTag);
+
+ }
+ }
+ }
+
+ public UnacknowledgedMessage remove(long deliveryTag)
+ {
+ synchronized (_lock)
+ {
+
+ UnacknowledgedMessage message = _map.remove(deliveryTag);
+ if(message != null)
+ {
+ _unackedSize -= message.message.getSize();
+ }
+
+ return message;
+ }
+ }
+
+ public void visit(Visitor visitor) throws AMQException
+ {
+ synchronized (_lock)
+ {
+ Collection<UnacknowledgedMessage> currentEntries = _map.values();
+ for (UnacknowledgedMessage msg : currentEntries)
+ {
+ visitor.callback(msg);
+ }
+ visitor.visitComplete();
+ }
+ }
+
+ public Object getLock()
+ {
+ return _lock;
+ }
+
+ public void add(long deliveryTag, UnacknowledgedMessage message)
+ {
+ synchronized (_lock)
+ {
+ _map.put(deliveryTag, message);
+ _unackedSize += message.message.getSize();
+ _lastDeliveryTag = deliveryTag;
+ }
+ }
+
+ public Collection<UnacknowledgedMessage> cancelAllMessages()
+ {
+ synchronized (_lock)
+ {
+ Collection<UnacknowledgedMessage> currentEntries = _map.values();
+ _map = new LinkedHashMap<Long, UnacknowledgedMessage>(_prefetchLimit);
+ _unackedSize = 0l;
+ return currentEntries;
}
}
- private UnacknowledgedMessage get(long key)
+ public void acknowledgeMessage(long deliveryTag, boolean multiple, TransactionalContext txnContext)
+ throws AMQException
{
- synchronized(_lock)
+ synchronized (_lock)
+ {
+ txnContext.acknowledgeMessage(deliveryTag, _lastDeliveryTag, multiple, this);
+ }
+ }
+
+ public int size()
+ {
+ synchronized (_lock)
+ {
+ return _map.size();
+ }
+ }
+
+ public void clear()
+ {
+ synchronized (_lock)
+ {
+ _map.clear();
+ _unackedSize = 0l;
+ }
+ }
+
+ public void drainTo(Collection<UnacknowledgedMessage> destination, long deliveryTag) throws AMQException
+ {
+ synchronized (_lock)
+ {
+ Iterator<Map.Entry<Long, UnacknowledgedMessage>> it = _map.entrySet().iterator();
+ while (it.hasNext())
+ {
+ Map.Entry<Long, UnacknowledgedMessage> unacked = it.next();
+
+ if (unacked.getKey() > deliveryTag)
+ {
+ //This should not occur now.
+ throw new AMQException("UnacknowledgedMessageMap is out of order:" + unacked.getKey() +
+ " When deliveryTag is:" + deliveryTag + "ES:" + _map.entrySet().toString());
+ }
+
+ it.remove();
+ _unackedSize -= unacked.getValue().message.getSize();
+
+ destination.add(unacked.getValue());
+ if (unacked.getKey() == deliveryTag)
+ {
+ break;
+ }
+ }
+ }
+ }
+
+// public void resendMessages(AMQProtocolSession protocolSession, int channelId) throws AMQException
+ public void resendMessages(AMQProtocolSession protocolSession, AMQChannel channel) throws AMQException
+ {
+ synchronized (_lock)
+ {
+ for (Map.Entry<Long, UnacknowledgedMessage> entry : _map.entrySet())
+ {
+ long deliveryTag = entry.getKey();
+ AMQShortString consumerTag = entry.getValue().consumerTag;
+ AMQMessage msg = entry.getValue().message;
+
+ if(consumerTag != null)
+ {
+// msg.writeDeliver(protocolSession, channelId, deliveryTag, consumerTag);
+ channel.deliver(msg, consumerTag, deliveryTag);
+ }
+ }
+ }
+ }
+
+ public UnacknowledgedMessage get(long key)
+ {
+ synchronized (_lock)
{
return _map.get(key);
}
}
+ public Set<Long> getDeliveryTags()
+ {
+ synchronized (_lock)
+ {
+ return _map.keySet();
+ }
+ }
+
private void collect(long key, List<UnacknowledgedMessage> msgs)
{
- synchronized(_lock)
+ synchronized (_lock)
{
- for(Map.Entry<Long, UnacknowledgedMessage> entry : _map.entrySet())
+ for (Map.Entry<Long, UnacknowledgedMessage> entry : _map.entrySet())
{
msgs.add(entry.getValue());
if (entry.getKey() == key)
{
break;
- }
+ }
}
}
}
-}
+ public long getUnacknowledgeBytes()
+ {
+ return _unackedSize;
+ }
+}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/Configurator.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/Configurator.java
index 5e3ac03ba7..379da94aa3 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/Configurator.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/configuration/Configurator.java
@@ -37,14 +37,15 @@ public class Configurator
{
private static final Logger _logger = Logger.getLogger(Configurator.class);
+
/**
- * Configure a given instance using the application configuration. Note that superclasses are <b>not</b>
+ * Configure a given instance using the supplied configuration. Note that superclasses are <b>not</b>
* currently configured but this could easily be added if required.
* @param instance the instance to configure
+ * @param config the configuration to use to configure the object
*/
- public static void configure(Object instance)
+ public static void configure(Object instance, Configuration config)
{
- final Configuration config = ApplicationRegistry.getInstance().getConfiguration();
for (Field f : instance.getClass().getDeclaredFields())
{
@@ -56,6 +57,18 @@ public class Configurator
}
}
+
+
+ /**
+ * Configure a given instance using the application configuration. Note that superclasses are <b>not</b>
+ * currently configured but this could easily be added if required.
+ * @param instance the instance to configure
+ */
+ public static void configure(Object instance)
+ {
+ configure(instance, ApplicationRegistry.getInstance().getConfiguration());
+ }
+
private static void setValueInField(Field f, Object instance, Configuration config, Configured annotation)
{
Class fieldClass = f.getType();
diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/VirtualHostConfiguration.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/VirtualHostConfiguration.java
index 9ecbf3d31a..361a21b284 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/configuration/VirtualHostConfiguration.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/configuration/VirtualHostConfiguration.java
@@ -28,7 +28,9 @@ import org.apache.qpid.server.registry.ApplicationRegistry;
import org.apache.qpid.server.exchange.Exchange;
import org.apache.qpid.server.exchange.ExchangeRegistry;
import org.apache.qpid.server.store.MessageStore;
+import org.apache.qpid.server.virtualhost.VirtualHost;
import org.apache.qpid.AMQException;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.log4j.Logger;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
@@ -112,6 +114,7 @@ public class VirtualHostConfiguration
}
_logger.info("VirtualHost:'" + prop + "'");
+ String virtualHost = prop.toString();
prop = _config.getProperty(path + "." + XML_BIND);
if (prop instanceof Collection)
@@ -120,16 +123,16 @@ public class VirtualHostConfiguration
_logger.debug("Number of Bindings: " + bindings);
for (int dest = 0; dest < bindings; dest++)
{
- loadBinding(path, dest);
+ loadBinding(virtualHost, path, dest);
}
}
else
{
- loadBinding(path, -1);
+ loadBinding(virtualHost,path, -1);
}
}
- private void loadBinding(String rootpath, int index) throws AMQException, ConfigurationException, URLSyntaxException
+ private void loadBinding(String virtualHost, String rootpath, int index) throws AMQException, ConfigurationException, URLSyntaxException
{
String path = rootpath + "." + XML_BIND;
if (index != -1)
@@ -145,7 +148,7 @@ public class VirtualHostConfiguration
try
{
- bind(binding);
+ bind(virtualHost, binding);
}
catch (AMQException amqe)
{
@@ -154,10 +157,10 @@ public class VirtualHostConfiguration
}
}
- private void bind(AMQBindingURL binding) throws AMQException, ConfigurationException
+ private void bind(String virtualHostName, AMQBindingURL binding) throws AMQException, ConfigurationException
{
- String queueName = binding.getQueueName();
+ AMQShortString queueName = binding.getQueueName();
// This will occur if the URL is a Topic
if (queueName == null)
@@ -168,9 +171,10 @@ public class VirtualHostConfiguration
}
//Get references to Broker Registries
- QueueRegistry queueRegistry = ApplicationRegistry.getInstance().getQueueRegistry();
- MessageStore messageStore = ApplicationRegistry.getInstance().getMessageStore();
- ExchangeRegistry exchangeRegistry = ApplicationRegistry.getInstance().getExchangeRegistry();
+ VirtualHost virtualHost = ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHost(virtualHostName);
+ QueueRegistry queueRegistry = virtualHost.getQueueRegistry();
+ MessageStore messageStore = virtualHost.getMessageStore();
+ ExchangeRegistry exchangeRegistry = virtualHost.getExchangeRegistry();
synchronized (queueRegistry)
{
@@ -183,7 +187,7 @@ public class VirtualHostConfiguration
queue = new AMQQueue(queueName,
Boolean.parseBoolean(binding.getOption(AMQBindingURL.OPTION_DURABLE)),
null /* These queues will have no owner */,
- false /* Therefore autodelete makes no sence */, queueRegistry);
+ false /* Therefore autodelete makes no sence */, virtualHost);
if (queue.isDurable())
{
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/AbstractExchange.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/AbstractExchange.java
index d5ca567308..8b4f41a7a0 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/exchange/AbstractExchange.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/exchange/AbstractExchange.java
@@ -21,9 +21,14 @@
package org.apache.qpid.server.exchange;
import org.apache.qpid.AMQException;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.server.management.AMQManagedObject;
import org.apache.qpid.server.management.Managable;
import org.apache.qpid.server.management.ManagedObject;
+import org.apache.qpid.server.management.ManagedObjectRegistry;
+import org.apache.qpid.server.virtualhost.VirtualHost;
+import org.apache.qpid.server.queue.QueueRegistry;
+import org.apache.qpid.server.registry.ApplicationRegistry;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
@@ -31,12 +36,16 @@ import javax.management.ObjectName;
public abstract class AbstractExchange implements Exchange, Managable
{
- private String _name;
+ private AMQShortString _name;
+
+
protected boolean _durable;
protected String _exchangeType;
protected int _ticket;
+ private VirtualHost _virtualHost;
+
protected ExchangeMBean _exchangeMbean;
/**
@@ -56,14 +65,19 @@ public abstract class AbstractExchange implements Exchange, Managable
super(ManagedExchange.class, ManagedExchange.TYPE);
}
+ public ManagedObject getParentObject()
+ {
+ return _virtualHost.getManagedObject();
+ }
+
public String getObjectInstanceName()
{
- return _name;
+ return _name.toString();
}
public String getName()
{
- return _name;
+ return _name.toString();
}
public String getExchangeType()
@@ -86,6 +100,7 @@ public abstract class AbstractExchange implements Exchange, Managable
return _autoDelete;
}
+ // Added exchangetype in the object name lets maangement apps to do any customization required
public ObjectName getObjectName() throws MalformedObjectNameException
{
String objNameString = super.getObjectName().toString();
@@ -93,9 +108,13 @@ public abstract class AbstractExchange implements Exchange, Managable
return new ObjectName(objNameString);
}
+ protected ManagedObjectRegistry getManagedObjectRegistry()
+ {
+ return ApplicationRegistry.getInstance().getManagedObjectRegistry();
+ }
} // End of MBean class
- public String getName()
+ public AMQShortString getName()
{
return _name;
}
@@ -107,8 +126,9 @@ public abstract class AbstractExchange implements Exchange, Managable
*/
protected abstract ExchangeMBean createMBean() throws AMQException;
- public void initialise(String name, boolean durable, int ticket, boolean autoDelete) throws AMQException
+ public void initialise(VirtualHost host, AMQShortString name, boolean durable, int ticket, boolean autoDelete) throws AMQException
{
+ _virtualHost = host;
_name = name;
_durable = durable;
_autoDelete = autoDelete;
@@ -150,4 +170,13 @@ public abstract class AbstractExchange implements Exchange, Managable
return _exchangeMbean;
}
+ public VirtualHost getVirtualHost()
+ {
+ return _virtualHost;
+ }
+
+ public QueueRegistry getQueueRegistry()
+ {
+ return getVirtualHost().getQueueRegistry();
+ }
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/DefaultExchangeFactory.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/DefaultExchangeFactory.java
index 8603bc34aa..86feb46bb6 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/exchange/DefaultExchangeFactory.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/exchange/DefaultExchangeFactory.java
@@ -22,6 +22,12 @@ package org.apache.qpid.server.exchange;
import org.apache.log4j.Logger;
import org.apache.qpid.AMQException;
+import org.apache.qpid.AMQChannelException;
+import org.apache.qpid.AMQUnknownExchangeType;
+import org.apache.qpid.server.virtualhost.VirtualHost;
+import org.apache.qpid.protocol.AMQConstant;
+import org.apache.qpid.exchange.ExchangeDefaults;
+import org.apache.qpid.framing.AMQShortString;
import java.util.HashMap;
import java.util.Map;
@@ -32,17 +38,19 @@ public class DefaultExchangeFactory implements ExchangeFactory
{
private static final Logger _logger = Logger.getLogger(DefaultExchangeFactory.class);
- private Map<String, Class<? extends Exchange>> _exchangeClassMap = new HashMap<String, Class<? extends Exchange>>();
+ private Map<AMQShortString, Class<? extends Exchange>> _exchangeClassMap = new HashMap<AMQShortString, Class<? extends Exchange>>();
+ private final VirtualHost _host;
- public DefaultExchangeFactory()
+ public DefaultExchangeFactory(VirtualHost host)
{
+ _host = host;
_exchangeClassMap.put(ExchangeDefaults.DIRECT_EXCHANGE_CLASS, org.apache.qpid.server.exchange.DestNameExchange.class);
_exchangeClassMap.put(ExchangeDefaults.TOPIC_EXCHANGE_CLASS, org.apache.qpid.server.exchange.DestWildExchange.class);
_exchangeClassMap.put(ExchangeDefaults.HEADERS_EXCHANGE_CLASS, org.apache.qpid.server.exchange.HeadersExchange.class);
_exchangeClassMap.put(ExchangeDefaults.FANOUT_EXCHANGE_CLASS, org.apache.qpid.server.exchange.FanoutExchange.class);
}
- public Exchange createExchange(String exchange, String type, boolean durable, boolean autoDelete,
+ public Exchange createExchange(AMQShortString exchange, AMQShortString type, boolean durable, boolean autoDelete,
int ticket)
throws AMQException
{
@@ -54,7 +62,7 @@ public class DefaultExchangeFactory implements ExchangeFactory
try
{
Exchange e = exchClass.newInstance();
- e.initialise(exchange, durable, ticket, autoDelete);
+ e.initialise(_host, exchange, durable, ticket, autoDelete);
return e;
}
catch (InstantiationException e)
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/DefaultExchangeRegistry.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/DefaultExchangeRegistry.java
index 02a8dbda6e..fb5b6763ba 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/exchange/DefaultExchangeRegistry.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/exchange/DefaultExchangeRegistry.java
@@ -20,10 +20,11 @@
*/
package org.apache.qpid.server.exchange;
+import org.apache.log4j.Logger;
import org.apache.qpid.AMQException;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.server.protocol.ExchangeInitialiser;
import org.apache.qpid.server.queue.AMQMessage;
-import org.apache.log4j.Logger;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
@@ -35,7 +36,7 @@ public class DefaultExchangeRegistry implements ExchangeRegistry
/**
* Maps from exchange name to exchange instance
*/
- private ConcurrentMap<String, Exchange> _exchangeMap = new ConcurrentHashMap<String, Exchange>();
+ private ConcurrentMap<AMQShortString, Exchange> _exchangeMap = new ConcurrentHashMap<AMQShortString, Exchange>();
private Exchange _defaultExchange;
@@ -66,7 +67,7 @@ public class DefaultExchangeRegistry implements ExchangeRegistry
_defaultExchange = exchange;
}
- public void unregisterExchange(String name, boolean inUse) throws AMQException
+ public void unregisterExchange(AMQShortString name, boolean inUse) throws AMQException
{
// TODO: check inUse argument
Exchange e = _exchangeMap.remove(name);
@@ -80,7 +81,7 @@ public class DefaultExchangeRegistry implements ExchangeRegistry
}
}
- public Exchange getExchange(String name)
+ public Exchange getExchange(AMQShortString name)
{
if(name == null || name.length() == 0)
@@ -101,7 +102,7 @@ public class DefaultExchangeRegistry implements ExchangeRegistry
*/
public void routeContent(AMQMessage payload) throws AMQException
{
- final String exchange = payload.getTransferBody().destination;
+ final AMQShortString exchange = payload.getTransferBody().destination;
final Exchange exch = getExchange(exchange);
// there is a small window of opportunity for the exchange to be deleted in between
// the JmsPublish being received (where the exchange is validated) and the final
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/DestNameExchange.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/DestNameExchange.java
index 872cde56e2..ac876bcb63 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/exchange/DestNameExchange.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/exchange/DestNameExchange.java
@@ -24,6 +24,7 @@ import org.apache.log4j.Logger;
import org.apache.qpid.AMQException;
import org.apache.qpid.framing.MessageTransferBody;
import org.apache.qpid.framing.FieldTable;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.server.management.MBeanConstructor;
import org.apache.qpid.server.management.MBeanDescription;
import org.apache.qpid.server.queue.AMQMessage;
@@ -84,21 +85,21 @@ public class DestNameExchange extends AbstractExchange
public TabularData bindings() throws OpenDataException
{
- Map<String, List<AMQQueue>> bindings = _index.getBindingsMap();
+ Map<AMQShortString, List<AMQQueue>> bindings = _index.getBindingsMap();
_bindingList = new TabularDataSupport(_bindinglistDataType);
- for (Map.Entry<String, List<AMQQueue>> entry : bindings.entrySet())
+ for (Map.Entry<AMQShortString, List<AMQQueue>> entry : bindings.entrySet())
{
- String key = entry.getKey();
+ AMQShortString key = entry.getKey();
List<String> queueList = new ArrayList<String>();
List<AMQQueue> queues = entry.getValue();
for (AMQQueue q : queues)
{
- queueList.add(q.getName());
+ queueList.add(q.getName().toString());
}
- Object[] bindingItemValues = {key, queueList.toArray(new String[0])};
+ Object[] bindingItemValues = {key.toString(), queueList.toArray(new String[0])};
CompositeData bindingData = new CompositeDataSupport(_bindingDataType, _bindingItemNames, bindingItemValues);
_bindingList.put(bindingData);
}
@@ -108,7 +109,7 @@ public class DestNameExchange extends AbstractExchange
public void createNewBinding(String queueName, String binding) throws JMException
{
- AMQQueue queue = ApplicationRegistry.getInstance().getQueueRegistry().getQueue(queueName);
+ AMQQueue queue = getQueueRegistry().getQueue(new AMQShortString(queueName));
if (queue == null)
{
throw new JMException("Queue \"" + queueName + "\" is not registered with the exchange.");
@@ -116,8 +117,8 @@ public class DestNameExchange extends AbstractExchange
try
{
- registerQueue(binding, queue, null);
- queue.bind(binding, DestNameExchange.this);
+ registerQueue(new AMQShortString(binding), queue, null);
+ queue.bind(new AMQShortString(binding), DestNameExchange.this);
}
catch (AMQException ex)
{
@@ -141,7 +142,12 @@ public class DestNameExchange extends AbstractExchange
}
}
- public void registerQueue(String routingKey, AMQQueue queue, FieldTable args) throws AMQException
+ public AMQShortString getType()
+ {
+ return ExchangeDefaults.DIRECT_EXCHANGE_CLASS;
+ }
+
+ public void registerQueue(AMQShortString routingKey, AMQQueue queue, FieldTable args) throws AMQException
{
assert queue != null;
assert routingKey != null;
@@ -155,7 +161,7 @@ public class DestNameExchange extends AbstractExchange
}
}
- public void deregisterQueue(String routingKey, AMQQueue queue) throws AMQException
+ public void deregisterQueue(AMQShortString routingKey, AMQQueue queue) throws AMQException
{
assert queue != null;
assert routingKey != null;
@@ -171,7 +177,7 @@ public class DestNameExchange extends AbstractExchange
{
MessageTransferBody transferBody = payload.getTransferBody();
- final String routingKey = transferBody.routingKey;
+ final AMQShortString routingKey = transferBody.routingKey;
final List<AMQQueue> queues = (routingKey == null) ? null : _index.get(routingKey);
if (queues == null || queues.isEmpty())
{
@@ -195,18 +201,18 @@ public class DestNameExchange extends AbstractExchange
for (AMQQueue q : queues)
{
- q.deliver(payload);
+ payload.enqueue(q);
}
}
}
- public boolean isBound(String routingKey, AMQQueue queue) throws AMQException
+ public boolean isBound(AMQShortString routingKey, AMQQueue queue) throws AMQException
{
final List<AMQQueue> queues = _index.get(routingKey);
return queues != null && queues.contains(queue);
}
- public boolean isBound(String routingKey) throws AMQException
+ public boolean isBound(AMQShortString routingKey) throws AMQException
{
final List<AMQQueue> queues = _index.get(routingKey);
return queues != null && !queues.isEmpty();
@@ -214,7 +220,7 @@ public class DestNameExchange extends AbstractExchange
public boolean isBound(AMQQueue queue) throws AMQException
{
- Map<String, List<AMQQueue>> bindings = _index.getBindingsMap();
+ Map<AMQShortString, List<AMQQueue>> bindings = _index.getBindingsMap();
for (List<AMQQueue> queues : bindings.values())
{
if (queues.contains(queue))
@@ -229,9 +235,4 @@ public class DestNameExchange extends AbstractExchange
{
return !_index.getBindingsMap().isEmpty();
}
-
- public String getType()
- {
- return ExchangeDefaults.DIRECT_EXCHANGE_CLASS;
- }
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/DestWildExchange.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/DestWildExchange.java
index 3064a7eabc..b94f5966cf 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/exchange/DestWildExchange.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/exchange/DestWildExchange.java
@@ -24,12 +24,14 @@ import org.apache.log4j.Logger;
import org.apache.qpid.AMQException;
import org.apache.qpid.framing.MessageTransferBody;
import org.apache.qpid.framing.FieldTable;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.server.management.MBeanConstructor;
import org.apache.qpid.server.management.MBeanDescription;
import org.apache.qpid.server.queue.AMQMessage;
import org.apache.qpid.server.queue.AMQQueue;
import org.apache.qpid.server.registry.ApplicationRegistry;
import org.apache.qpid.exchange.ExchangeDefaults;
+import org.apache.qpid.server.virtualhost.VirtualHost;
import javax.management.JMException;
import javax.management.MBeanException;
@@ -44,7 +46,7 @@ public class DestWildExchange extends AbstractExchange
{
private static final Logger _logger = Logger.getLogger(DestWildExchange.class);
- private ConcurrentHashMap<String, List<AMQQueue>> _routingKey2queues = new ConcurrentHashMap<String, List<AMQQueue>>();
+ private ConcurrentHashMap<AMQShortString, List<AMQQueue>> _routingKey2queues = new ConcurrentHashMap<AMQShortString, List<AMQQueue>>();
/**
* DestWildExchangeMBean class implements the management interface for the
@@ -88,18 +90,18 @@ public class DestWildExchange extends AbstractExchange
public TabularData bindings() throws OpenDataException
{
_bindingList = new TabularDataSupport(_bindinglistDataType);
- for (Map.Entry<String, List<AMQQueue>> entry : _routingKey2queues.entrySet())
+ for (Map.Entry<AMQShortString, List<AMQQueue>> entry : _routingKey2queues.entrySet())
{
- String key = entry.getKey();
+ AMQShortString key = entry.getKey();
List<String> queueList = new ArrayList<String>();
List<AMQQueue> queues = entry.getValue();
for (AMQQueue q : queues)
{
- queueList.add(q.getName());
+ queueList.add(q.getName().toString());
}
- Object[] bindingItemValues = {key, queueList.toArray(new String[0])};
+ Object[] bindingItemValues = {key.toString(), queueList.toArray(new String[0])};
CompositeData bindingData = new CompositeDataSupport(_bindingDataType, _bindingItemNames, bindingItemValues);
_bindingList.put(bindingData);
}
@@ -109,14 +111,14 @@ public class DestWildExchange extends AbstractExchange
public void createNewBinding(String queueName, String binding) throws JMException
{
- AMQQueue queue = ApplicationRegistry.getInstance().getQueueRegistry().getQueue(queueName);
+ AMQQueue queue = getQueueRegistry().getQueue(new AMQShortString(queueName));
if (queue == null)
throw new JMException("Queue \"" + queueName + "\" is not registered with the exchange.");
try
{
- registerQueue(binding, queue, null);
- queue.bind(binding, DestWildExchange.this);
+ registerQueue(new AMQShortString(binding), queue, null);
+ queue.bind(new AMQShortString(binding), DestWildExchange.this);
}
catch (AMQException ex)
{
@@ -127,7 +129,12 @@ public class DestWildExchange extends AbstractExchange
} // End of MBean class
- public synchronized void registerQueue(String routingKey, AMQQueue queue, FieldTable args) throws AMQException
+ public AMQShortString getType()
+ {
+ return ExchangeDefaults.TOPIC_EXCHANGE_CLASS;
+ }
+
+ public synchronized void registerQueue(AMQShortString routingKey, AMQQueue queue, FieldTable args) throws AMQException
{
assert queue != null;
assert routingKey != null;
@@ -155,7 +162,7 @@ public class DestWildExchange extends AbstractExchange
{
MessageTransferBody transferBody = payload.getTransferBody();
- final String routingKey = transferBody.routingKey;
+ final AMQShortString routingKey = transferBody.routingKey;
List<AMQQueue> queues = _routingKey2queues.get(routingKey);
// if we have no registered queues we have nothing to do
// TODO: add support for the immediate flag
@@ -172,18 +179,21 @@ public class DestWildExchange extends AbstractExchange
// TODO: modify code generator to add clone() method then clone the deliver body
// without this addition we have a race condition - we will be modifying the body
// before the encoder has encoded the body for delivery
- q.deliver(payload);
+// q.deliver(payload);
+ payload.enqueue(q);
+// HERE!!
+// q.process(storeContext, payload);
}
}
- public boolean isBound(String routingKey, AMQQueue queue) throws AMQException
+ public boolean isBound(AMQShortString routingKey, AMQQueue queue) throws AMQException
{
List<AMQQueue> queues = _routingKey2queues.get(routingKey);
return queues != null && queues.contains(queue);
}
- public boolean isBound(String routingKey) throws AMQException
+ public boolean isBound(AMQShortString routingKey) throws AMQException
{
List<AMQQueue> queues = _routingKey2queues.get(routingKey);
return queues != null && !queues.isEmpty();
@@ -206,7 +216,7 @@ public class DestWildExchange extends AbstractExchange
return !_routingKey2queues.isEmpty();
}
- public synchronized void deregisterQueue(String routingKey, AMQQueue queue) throws AMQException
+ public synchronized void deregisterQueue(AMQShortString routingKey, AMQQueue queue) throws AMQException
{
assert queue != null;
assert routingKey != null;
@@ -242,10 +252,4 @@ public class DestWildExchange extends AbstractExchange
throw new AMQException("Exception occured in creating the topic exchenge mbean", ex);
}
}
-
-
- public String getType()
- {
- return ExchangeDefaults.TOPIC_EXCHANGE_CLASS;
- }
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/Exchange.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/Exchange.java
index 9fcbe2a871..c012a1c1c9 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/exchange/Exchange.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/exchange/Exchange.java
@@ -22,15 +22,17 @@ package org.apache.qpid.server.exchange;
import org.apache.qpid.AMQException;
import org.apache.qpid.framing.FieldTable;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.server.queue.AMQQueue;
import org.apache.qpid.server.queue.AMQMessage;
+import org.apache.qpid.server.virtualhost.VirtualHost;
public interface Exchange
{
- String getName();
- String getType();
+ AMQShortString getName();
+ AMQShortString getType();
- void initialise(String name, boolean durable, int ticket, boolean autoDelete) throws AMQException;
+ void initialise(VirtualHost host, AMQShortString name, boolean durable, int ticket, boolean autoDelete) throws AMQException;
boolean isDurable();
@@ -43,9 +45,9 @@ public interface Exchange
void close() throws AMQException;
- void registerQueue(String routingKey, AMQQueue queue, FieldTable args) throws AMQException;
+ void registerQueue(AMQShortString routingKey, AMQQueue queue, FieldTable args) throws AMQException;
- void deregisterQueue(String routingKey, AMQQueue queue) throws AMQException;
+ void deregisterQueue(AMQShortString routingKey, AMQQueue queue) throws AMQException;
void route(AMQMessage message) throws AMQException;
@@ -56,7 +58,7 @@ public interface Exchange
* @return
* @throws AMQException
*/
- boolean isBound(String routingKey, AMQQueue queue) throws AMQException;
+ boolean isBound(AMQShortString routingKey, AMQQueue queue) throws AMQException;
/**
* Determines whether a message is routing to any queue using a specific routing key
@@ -64,7 +66,7 @@ public interface Exchange
* @return
* @throws AMQException
*/
- boolean isBound(String routingKey) throws AMQException;
+ boolean isBound(AMQShortString routingKey) throws AMQException;
boolean isBound(AMQQueue queue) throws AMQException;
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeFactory.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeFactory.java
index 37ba883bc3..e07fd0b8fc 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeFactory.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeFactory.java
@@ -21,11 +21,12 @@
package org.apache.qpid.server.exchange;
import org.apache.qpid.AMQException;
+import org.apache.qpid.framing.AMQShortString;
public interface ExchangeFactory
{
- Exchange createExchange(String exchange, String type, boolean durable, boolean autoDelete,
+ Exchange createExchange(AMQShortString exchange, AMQShortString type, boolean durable, boolean autoDelete,
int ticket)
throws AMQException;
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeRegistry.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeRegistry.java
index 2fc64135a2..24884d20d7 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeRegistry.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeRegistry.java
@@ -21,6 +21,7 @@
package org.apache.qpid.server.exchange;
import org.apache.qpid.AMQException;
+import org.apache.qpid.framing.AMQShortString;
public interface ExchangeRegistry extends MessageRouter
@@ -34,9 +35,9 @@ public interface ExchangeRegistry extends MessageRouter
* @throws ExchangeInUseException when the exchange cannot be deleted because it is in use
* @throws AMQException
*/
- void unregisterExchange(String name, boolean inUse) throws ExchangeInUseException, AMQException;
+ void unregisterExchange(AMQShortString name, boolean inUse) throws ExchangeInUseException, AMQException;
- Exchange getExchange(String name);
+ Exchange getExchange(AMQShortString name);
void setDefaultExchange(Exchange exchange);
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/FanoutExchange.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/FanoutExchange.java
index 6c1db77995..3077cc52c6 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/exchange/FanoutExchange.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/exchange/FanoutExchange.java
@@ -1,3 +1,23 @@
+/*
+ *
+ * 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.log4j.Logger;
@@ -6,6 +26,7 @@ import org.apache.qpid.server.management.MBeanConstructor;
import org.apache.qpid.server.queue.AMQQueue;
import org.apache.qpid.server.queue.AMQMessage;
import org.apache.qpid.server.registry.ApplicationRegistry;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.framing.FieldTable;
import org.apache.qpid.framing.MessageTransferBody;
import org.apache.qpid.AMQException;
@@ -85,7 +106,7 @@ public class FanoutExchange extends AbstractExchange
public void createNewBinding(String queueName, String binding) throws JMException
{
- AMQQueue queue = ApplicationRegistry.getInstance().getQueueRegistry().getQueue(queueName);
+ AMQQueue queue = getQueueRegistry().getQueue(new AMQShortString(queueName));
if (queue == null)
{
throw new JMException("Queue \"" + queueName + "\" is not registered with the exchange.");
@@ -93,8 +114,8 @@ public class FanoutExchange extends AbstractExchange
try
{
- registerQueue(binding, queue, null);
- queue.bind(binding, FanoutExchange.this);
+ registerQueue(new AMQShortString(binding), queue, null);
+ queue.bind(new AMQShortString(binding), FanoutExchange.this);
}
catch (AMQException ex)
{
@@ -118,12 +139,12 @@ public class FanoutExchange extends AbstractExchange
}
}
- public String getType()
+ public AMQShortString getType()
{
return ExchangeDefaults.FANOUT_EXCHANGE_CLASS;
}
- public void registerQueue(String routingKey, AMQQueue queue, FieldTable args) throws AMQException
+ public void registerQueue(AMQShortString routingKey, AMQQueue queue, FieldTable args) throws AMQException
{
assert queue != null;
@@ -138,7 +159,7 @@ public class FanoutExchange extends AbstractExchange
}
}
- public void deregisterQueue(String routingKey, AMQQueue queue) throws AMQException
+ public void deregisterQueue(AMQShortString routingKey, AMQQueue queue) throws AMQException
{
assert queue != null;
assert routingKey != null;
@@ -174,17 +195,17 @@ public class FanoutExchange extends AbstractExchange
for (AMQQueue q : _queues)
{
- q.deliver(payload);
+ payload.enqueue(q);
}
}
}
- public boolean isBound(String routingKey, AMQQueue queue) throws AMQException
+ public boolean isBound(AMQShortString routingKey, AMQQueue queue) throws AMQException
{
return _queues.contains(queue);
}
- public boolean isBound(String routingKey) throws AMQException
+ public boolean isBound(AMQShortString routingKey) throws AMQException
{
return _queues != null && !_queues.isEmpty();
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/HeadersBinding.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/HeadersBinding.java
index 1c63a5571e..cf10f219aa 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/exchange/HeadersBinding.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/exchange/HeadersBinding.java
@@ -34,7 +34,7 @@ class HeadersBinding
{
private static final Logger _logger = Logger.getLogger(HeadersBinding.class);
- private final FieldTable _mappings = new FieldTable();
+ private final FieldTable _mappings;
private final Set<String> required = new HashSet<String>();
private final Map<String,Object> matches = new HashMap<String,Object>();
private boolean matchAny;
@@ -91,12 +91,7 @@ class HeadersBinding
HeadersBinding(FieldTable mappings)
{
- Enumeration propertyNames = mappings.getPropertyNames();
- while(propertyNames.hasMoreElements())
- {
- String propName = (String) propertyNames.nextElement();
- _mappings.put(propName, mappings.getObject(propName));
- }
+ _mappings = mappings;
initMappings();
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/HeadersExchange.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/HeadersExchange.java
index 2829344dd5..0f98c0de41 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/exchange/HeadersExchange.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/exchange/HeadersExchange.java
@@ -22,6 +22,7 @@ package org.apache.qpid.server.exchange;
import org.apache.log4j.Logger;
import org.apache.qpid.AMQException;
+import org.apache.qpid.exchange.ExchangeDefaults;
import org.apache.qpid.framing.*;
import org.apache.qpid.server.management.MBeanConstructor;
import org.apache.qpid.server.management.MBeanDescription;
@@ -111,7 +112,7 @@ public class HeadersExchange extends AbstractExchange
for (Iterator<Registration> itr = _bindings.iterator(); itr.hasNext();)
{
Registration registration = itr.next();
- String queueName = registration.queue.getName();
+ String queueName = registration.queue.getName().toString();
HeadersBinding headers = registration.binding;
FieldTable headerMappings = headers.getMappings();
@@ -146,11 +147,11 @@ public class HeadersExchange extends AbstractExchange
* <attributename>=<value>,<attributename>=<value>,...
* @param queueName
* @param binding
- * @throws JMException
+ * @throws javax.management.JMException
*/
public void createNewBinding(String queueName, String binding) throws JMException
{
- AMQQueue queue = ApplicationRegistry.getInstance().getQueueRegistry().getQueue(queueName);
+ AMQQueue queue = getQueueRegistry().getQueue(new AMQShortString(queueName));
if (queue == null)
{
@@ -174,13 +175,18 @@ public class HeadersExchange extends AbstractExchange
} // End of MBean class
- public void registerQueue(String routingKey, AMQQueue queue, FieldTable args) throws AMQException
+ public AMQShortString getType()
+ {
+ return ExchangeDefaults.HEADERS_EXCHANGE_CLASS;
+ }
+
+ public void registerQueue(AMQShortString routingKey, AMQQueue queue, FieldTable args) throws AMQException
{
_logger.debug("Exchange " + getName() + ": Binding " + queue.getName() + " with " + args);
_bindings.add(new Registration(new HeadersBinding(args), queue));
}
- public void deregisterQueue(String routingKey, AMQQueue queue) throws AMQException
+ public void deregisterQueue(AMQShortString routingKey, AMQQueue queue) throws AMQException
{
_logger.debug("Exchange " + getName() + ": Unbinding " + queue.getName());
_bindings.remove(new Registration(null, queue));
@@ -193,7 +199,7 @@ public class HeadersExchange extends AbstractExchange
{
_logger.debug("Exchange " + getName() + ": routing message with headers " + headers);
}
- boolean delivered = false;
+ boolean routed = false;
for (Registration e : _bindings)
{
if (e.binding.matches(headers))
@@ -203,11 +209,11 @@ public class HeadersExchange extends AbstractExchange
_logger.debug("Exchange " + getName() + ": delivering message with headers " +
headers + " to " + e.queue.getName());
}
- e.queue.deliver(payload);
- delivered = true;
+ payload.enqueue(e.queue);
+ routed = true;
}
}
- if (!delivered)
+ if (!routed)
{
String msg = "Exchange " + getName() + ": message not routable.";
@@ -224,12 +230,12 @@ public class HeadersExchange extends AbstractExchange
}
}
- public boolean isBound(String routingKey, AMQQueue queue) throws AMQException
+ public boolean isBound(AMQShortString routingKey, AMQQueue queue) throws AMQException
{
return isBound(queue);
}
- public boolean isBound(String routingKey) throws AMQException
+ public boolean isBound(AMQShortString routingKey) throws AMQException
{
return hasBindings();
}
@@ -285,9 +291,4 @@ public class HeadersExchange extends AbstractExchange
return o instanceof Registration && ((Registration) o).queue.equals(queue);
}
}
-
- public String getType()
- {
- return ExchangeDefaults.HEADERS_EXCHANGE_CLASS;
- }
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/Index.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/Index.java
index 485c4739bd..8527a68862 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/exchange/Index.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/exchange/Index.java
@@ -21,6 +21,7 @@
package org.apache.qpid.server.exchange;
import org.apache.qpid.server.queue.AMQQueue;
+import org.apache.qpid.framing.AMQShortString;
import java.util.List;
import java.util.Map;
@@ -35,10 +36,10 @@ import java.util.concurrent.CopyOnWriteArrayList;
*/
class Index
{
- private ConcurrentMap<String, List<AMQQueue>> _index
- = new ConcurrentHashMap<String, List<AMQQueue>>();
+ private ConcurrentMap<AMQShortString, List<AMQQueue>> _index
+ = new ConcurrentHashMap<AMQShortString, List<AMQQueue>>();
- synchronized boolean add(String key, AMQQueue queue)
+ synchronized boolean add(AMQShortString key, AMQQueue queue)
{
List<AMQQueue> queues = _index.get(key);
if(queues == null)
@@ -62,7 +63,7 @@ class Index
}
}
- synchronized boolean remove(String key, AMQQueue queue)
+ synchronized boolean remove(AMQShortString key, AMQQueue queue)
{
List<AMQQueue> queues = _index.get(key);
if (queues != null)
@@ -77,13 +78,13 @@ class Index
return false;
}
- List<AMQQueue> get(String key)
+ List<AMQQueue> get(AMQShortString key)
{
return _index.get(key);
}
- Map<String, List<AMQQueue>> getBindingsMap()
+ Map<AMQShortString, List<AMQQueue>> getBindingsMap()
{
- return new HashMap<String, List<AMQQueue>>(_index);
+ return new HashMap<AMQShortString, List<AMQQueue>>(_index);
}
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/MessageRouter.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/MessageRouter.java
index 70b80f65da..7508e80f7f 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/exchange/MessageRouter.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/exchange/MessageRouter.java
@@ -20,8 +20,8 @@
*/
package org.apache.qpid.server.exchange;
-import org.apache.qpid.server.queue.AMQMessage;
import org.apache.qpid.AMQException;
+import org.apache.qpid.server.queue.AMQMessage;
/**
* Separated out from the ExchangeRegistry interface to allow components
@@ -33,6 +33,7 @@ public interface MessageRouter
/**
* Routes content through exchanges, delivering it to 1 or more queues.
* @param message the message to be routed
+ *
* @throws org.apache.qpid.AMQException if something goes wrong delivering data
*/
void routeContent(AMQMessage message) throws AMQException;
diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/ArithmeticExpression.java b/java/broker/src/main/java/org/apache/qpid/server/filter/ArithmeticExpression.java
index 0aa5739c1c..1b3b116fd0 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/filter/ArithmeticExpression.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/filter/ArithmeticExpression.java
@@ -21,10 +21,9 @@ package org.apache.qpid.server.filter;
//
+import org.apache.qpid.AMQException;
import org.apache.qpid.server.queue.AMQMessage;
-import javax.jms.JMSException;
-
/**
* An expression which performs an operation on two expression values
*
@@ -58,7 +57,8 @@ public abstract class ArithmeticExpression extends BinaryExpression {
throw new RuntimeException("Cannot call plus operation on: " + lvalue + " and: " + rvalue);
}
- public String getExpressionSymbol() {
+ public String getExpressionSymbol()
+ {
return "+";
}
};
@@ -193,7 +193,8 @@ public abstract class ArithmeticExpression extends BinaryExpression {
}
}
- public Object evaluate(AMQMessage message) throws JMSException {
+ public Object evaluate(AMQMessage message) throws AMQException
+ {
Object lvalue = left.evaluate(message);
if (lvalue == null) {
return null;
diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/BooleanExpression.java b/java/broker/src/main/java/org/apache/qpid/server/filter/BooleanExpression.java
index b66de3fbc5..122527d4f3 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/filter/BooleanExpression.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/filter/BooleanExpression.java
@@ -21,10 +21,10 @@ package org.apache.qpid.server.filter;
//
+import org.apache.qpid.AMQException;
import org.apache.qpid.server.queue.AMQMessage;
-import org.apache.qpid.server.message.jms.JMSMessage;
-import javax.jms.JMSException;
+
/**
@@ -33,13 +33,14 @@ import javax.jms.JMSException;
*
* @version $Revision$
*/
-public interface BooleanExpression extends Expression {
-
+public interface BooleanExpression extends Expression
+{
+
/**
* @param message
* @return true if the expression evaluates to Boolean.TRUE.
- * @throws JMSException
+ * @throws AMQException
*/
- public boolean matches(AMQMessage message) throws JMSException;
+ public boolean matches(AMQMessage message) throws AMQException;
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/ComparisonExpression.java b/java/broker/src/main/java/org/apache/qpid/server/filter/ComparisonExpression.java
index 13d278cf65..25d588a36f 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/filter/ComparisonExpression.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/filter/ComparisonExpression.java
@@ -20,15 +20,13 @@ package org.apache.qpid.server.filter;
// Based on like named file from r450141 of the Apache ActiveMQ project <http://www.activemq.org/site/home.html>
//
+import org.apache.qpid.AMQException;
import org.apache.qpid.server.queue.AMQMessage;
-import org.apache.qpid.server.message.jms.JMSMessage;
import java.util.HashSet;
import java.util.List;
import java.util.regex.Pattern;
-import javax.jms.JMSException;
-
/**
* A filter performing a comparison of two objects
*
@@ -123,7 +121,7 @@ public abstract class ComparisonExpression extends BinaryExpression implements B
/**
* org.apache.activemq.filter.Expression#evaluate(MessageEvaluationContext)
*/
- public Object evaluate(AMQMessage message) throws JMSException {
+ public Object evaluate(AMQMessage message) throws AMQException {
Object rv = this.getRight().evaluate(message);
@@ -139,7 +137,7 @@ public abstract class ComparisonExpression extends BinaryExpression implements B
return likePattern.matcher((String) rv).matches() ? Boolean.TRUE : Boolean.FALSE;
}
- public boolean matches(AMQMessage message) throws JMSException {
+ public boolean matches(AMQMessage message) throws AMQException {
Object object = evaluate(message);
return object!=null && object==Boolean.TRUE;
}
@@ -199,7 +197,7 @@ public abstract class ComparisonExpression extends BinaryExpression implements B
private static BooleanExpression doCreateEqual(Expression left, Expression right) {
return new ComparisonExpression(left, right) {
- public Object evaluate(AMQMessage message) throws JMSException {
+ public Object evaluate(AMQMessage message) throws AMQException {
Object lv = left.evaluate(message);
Object rv = right.evaluate(message);
@@ -340,7 +338,8 @@ public abstract class ComparisonExpression extends BinaryExpression implements B
super(left, right);
}
- public Object evaluate(AMQMessage message) throws JMSException {
+ public Object evaluate(AMQMessage message) throws AMQException
+ {
Comparable lv = (Comparable) left.evaluate(message);
if (lv == null) {
return null;
@@ -457,7 +456,7 @@ public abstract class ComparisonExpression extends BinaryExpression implements B
protected abstract boolean asBoolean(int answer);
- public boolean matches(AMQMessage message) throws JMSException {
+ public boolean matches(AMQMessage message) throws AMQException {
Object object = evaluate(message);
return object!=null && object==Boolean.TRUE;
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/ConstantExpression.java b/java/broker/src/main/java/org/apache/qpid/server/filter/ConstantExpression.java
index 9bde712da2..a4aea35079 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/filter/ConstantExpression.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/filter/ConstantExpression.java
@@ -20,28 +20,31 @@ package org.apache.qpid.server.filter;
// Based on like named file from r450141 of the Apache ActiveMQ project <http://www.activemq.org/site/home.html>
//
+import org.apache.qpid.AMQException;
import org.apache.qpid.server.queue.AMQMessage;
-import org.apache.qpid.server.message.jms.JMSMessage;
import java.math.BigDecimal;
-import javax.jms.JMSException;
-
/**
* Represents a constant expression
- *
+ *
* @version $Revision$
*/
-public class ConstantExpression implements Expression {
+public class ConstantExpression implements Expression
+{
- static class BooleanConstantExpression extends ConstantExpression implements BooleanExpression {
- public BooleanConstantExpression(Object value) {
+ static class BooleanConstantExpression extends ConstantExpression implements BooleanExpression
+ {
+ public BooleanConstantExpression(Object value)
+ {
super(value);
}
- public boolean matches(AMQMessage message) throws JMSException {
+
+ public boolean matches(AMQMessage message) throws AMQException
+ {
Object object = evaluate(message);
- return object!=null && object==Boolean.TRUE;
- }
+ return object != null && object == Boolean.TRUE;
+ }
}
public static final BooleanConstantExpression NULL = new BooleanConstantExpression(null);
@@ -50,73 +53,92 @@ public class ConstantExpression implements Expression {
private Object value;
- public static ConstantExpression createFromDecimal(String text) {
-
- // Strip off the 'l' or 'L' if needed.
- if( text.endsWith("l") || text.endsWith("L") )
- text = text.substring(0, text.length()-1);
-
- Number value;
- try {
- value = new Long(text);
- } catch ( NumberFormatException e) {
- // The number may be too big to fit in a long.
- value = new BigDecimal(text);
- }
-
+ public static ConstantExpression createFromDecimal(String text)
+ {
+
+ // Strip off the 'l' or 'L' if needed.
+ if (text.endsWith("l") || text.endsWith("L"))
+ {
+ text = text.substring(0, text.length() - 1);
+ }
+
+ Number value;
+ try
+ {
+ value = new Long(text);
+ }
+ catch (NumberFormatException e)
+ {
+ // The number may be too big to fit in a long.
+ value = new BigDecimal(text);
+ }
+
long l = value.longValue();
- if (Integer.MIN_VALUE <= l && l <= Integer.MAX_VALUE) {
+ if (Integer.MIN_VALUE <= l && l <= Integer.MAX_VALUE)
+ {
value = new Integer(value.intValue());
}
return new ConstantExpression(value);
}
- public static ConstantExpression createFromHex(String text) {
+ public static ConstantExpression createFromHex(String text)
+ {
Number value = new Long(Long.parseLong(text.substring(2), 16));
long l = value.longValue();
- if (Integer.MIN_VALUE <= l && l <= Integer.MAX_VALUE) {
+ if (Integer.MIN_VALUE <= l && l <= Integer.MAX_VALUE)
+ {
value = new Integer(value.intValue());
}
return new ConstantExpression(value);
}
- public static ConstantExpression createFromOctal(String text) {
+ public static ConstantExpression createFromOctal(String text)
+ {
Number value = new Long(Long.parseLong(text, 8));
long l = value.longValue();
- if (Integer.MIN_VALUE <= l && l <= Integer.MAX_VALUE) {
+ if (Integer.MIN_VALUE <= l && l <= Integer.MAX_VALUE)
+ {
value = new Integer(value.intValue());
}
return new ConstantExpression(value);
}
- public static ConstantExpression createFloat(String text) {
+ public static ConstantExpression createFloat(String text)
+ {
Number value = new Double(text);
return new ConstantExpression(value);
}
- public ConstantExpression(Object value) {
+ public ConstantExpression(Object value)
+ {
this.value = value;
}
- public Object evaluate(AMQMessage message) throws JMSException {
+ public Object evaluate(AMQMessage message) throws AMQException
+ {
return value;
}
- public Object getValue() {
+ public Object getValue()
+ {
return value;
- }
+ }
/**
* @see java.lang.Object#toString()
*/
- public String toString() {
- if (value == null) {
+ public String toString()
+ {
+ if (value == null)
+ {
return "NULL";
}
- if (value instanceof Boolean) {
+ if (value instanceof Boolean)
+ {
return ((Boolean) value).booleanValue() ? "TRUE" : "FALSE";
}
- if (value instanceof String) {
+ if (value instanceof String)
+ {
return encodeString((String) value);
}
return value.toString();
@@ -127,7 +149,8 @@ public class ConstantExpression implements Expression {
*
* @see java.lang.Object#hashCode()
*/
- public int hashCode() {
+ public int hashCode()
+ {
return toString().hashCode();
}
@@ -136,9 +159,11 @@ public class ConstantExpression implements Expression {
*
* @see java.lang.Object#equals(java.lang.Object)
*/
- public boolean equals(Object o) {
+ public boolean equals(Object o)
+ {
- if (o == null || !this.getClass().equals(o.getClass())) {
+ if (o == null || !this.getClass().equals(o.getClass()))
+ {
return false;
}
return toString().equals(o.toString());
@@ -153,12 +178,15 @@ public class ConstantExpression implements Expression {
* @param s
* @return
*/
- public static String encodeString(String s) {
+ public static String encodeString(String s)
+ {
StringBuffer b = new StringBuffer();
b.append('\'');
- for (int i = 0; i < s.length(); i++) {
+ for (int i = 0; i < s.length(); i++)
+ {
char c = s.charAt(i);
- if (c == '\'') {
+ if (c == '\'')
+ {
b.append(c);
}
b.append(c);
@@ -166,5 +194,5 @@ public class ConstantExpression implements Expression {
b.append('\'');
return b.toString();
}
-
+
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/Expression.java b/java/broker/src/main/java/org/apache/qpid/server/filter/Expression.java
index a15c15fb91..4a2130e767 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/filter/Expression.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/filter/Expression.java
@@ -21,10 +21,8 @@ package org.apache.qpid.server.filter;
// Based on like named file from r450141 of the Apache ActiveMQ project <http://www.activemq.org/site/home.html>
//
+import org.apache.qpid.AMQException;
import org.apache.qpid.server.queue.AMQMessage;
-import org.apache.qpid.server.message.jms.JMSMessage;
-
-import javax.jms.JMSException;
/**
@@ -32,11 +30,12 @@ import javax.jms.JMSException;
*
* @version $Revision$
*/
-public interface Expression {
+public interface Expression
+{
/**
* @return the value of this expression
*/
- public Object evaluate(AMQMessage message) throws JMSException;
+ public Object evaluate(AMQMessage message) throws AMQException;
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/FilterManagerFactory.java b/java/broker/src/main/java/org/apache/qpid/server/filter/FilterManagerFactory.java
index 49f99132ef..311f0680ec 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/filter/FilterManagerFactory.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/filter/FilterManagerFactory.java
@@ -20,13 +20,9 @@
*/
package org.apache.qpid.server.filter;
-import org.apache.qpid.framing.FieldTable;
import org.apache.qpid.AMQException;
import org.apache.qpid.common.AMQPFilterTypes;
-//import org.slf4j.Logger;
-//import org.slf4j.LoggerFactory;
-
-import java.util.Iterator;
+import org.apache.qpid.framing.FieldTable;
public class FilterManagerFactory
@@ -45,29 +41,24 @@ public class FilterManagerFactory
manager = new SimpleFilterManager();
- Iterator it = filters.keySet().iterator();
- _logger.info("Processing filters:");
- while (it.hasNext())
+ if(filters.containsKey(AMQPFilterTypes.JMS_SELECTOR.getValue()))
{
- String key = (String) it.next();
- _logger.info("filter:" + key);
- if (key.equals(AMQPFilterTypes.JMS_SELECTOR.getValue()))
- {
- String selector = (String) filters.get(key);
-
- if (selector != null && !selector.equals(""))
- {
- manager.add(new JMSSelectorFilter(selector));
- }
- }
+ String selector = filters.getString(AMQPFilterTypes.JMS_SELECTOR.getValue());
- if (key.equals(AMQPFilterTypes.NO_CONSUME.getValue()))
+ if (selector != null && !selector.equals(""))
{
- manager.add(new NoConsumerFilter());
+ manager.add(new JMSSelectorFilter(selector));
}
}
+ if (filters.containsKey(AMQPFilterTypes.NO_CONSUME.getValue()))
+ {
+ manager.add(new NoConsumerFilter());
+ }
+
+
+
//If we added no filters don't bear the overhead of having an filter manager
if (!manager.hasFilters())
{
@@ -76,7 +67,7 @@ public class FilterManagerFactory
}
else
{
- _logger.info("No Filters found.");
+ _logger.debug("No Filters found.");
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/JMSSelectorFilter.java b/java/broker/src/main/java/org/apache/qpid/server/filter/JMSSelectorFilter.java
index 4884067237..cba487c31e 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/filter/JMSSelectorFilter.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/filter/JMSSelectorFilter.java
@@ -20,15 +20,13 @@
*/
package org.apache.qpid.server.filter;
-import org.apache.qpid.server.queue.AMQMessage;
-import org.apache.qpid.server.filter.jms.selector.SelectorParser;
+import org.apache.log4j.Logger;
import org.apache.qpid.AMQException;
import org.apache.qpid.AMQInvalidSelectorException;
-import org.apache.log4j.Logger;
+import org.apache.qpid.server.filter.jms.selector.SelectorParser;
+import org.apache.qpid.server.queue.AMQMessage;
-import javax.jms.InvalidSelectorException;
-import javax.jms.JMSException;
public class JMSSelectorFilter implements MessageFilter
{
@@ -43,16 +41,8 @@ public class JMSSelectorFilter implements MessageFilter
_logger.info("Created JMSSelectorFilter with selector:" + _selector);
- try
- {
- _matcher = new SelectorParser().parse(selector);
- }
- catch (InvalidSelectorException e)
- {
- // fixme
- // Is this the correct way of throwing exception
- throw new AMQInvalidSelectorException(e.getMessage());
- }
+ _matcher = new SelectorParser().parse(selector);
+
}
@@ -64,7 +54,7 @@ public class JMSSelectorFilter implements MessageFilter
_logger.info(message + " match(" + match + ") selector(" + System.identityHashCode(_selector) + "):" + _selector);
return match;
}
- catch (JMSException e)
+ catch (AMQException e)
{
//fixme this needs to be sorted.. it shouldn't happen
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/LogicExpression.java b/java/broker/src/main/java/org/apache/qpid/server/filter/LogicExpression.java
index 714d8c23f5..dea6092b8a 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/filter/LogicExpression.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/filter/LogicExpression.java
@@ -20,10 +20,8 @@ package org.apache.qpid.server.filter;
// Based on like named file from r450141 of the Apache ActiveMQ project <http://www.activemq.org/site/home.html>
//
+import org.apache.qpid.AMQException;
import org.apache.qpid.server.queue.AMQMessage;
-import org.apache.qpid.server.message.jms.JMSMessage;
-
-import javax.jms.JMSException;
/**
* A filter performing a comparison of two objects
@@ -35,7 +33,7 @@ public abstract class LogicExpression extends BinaryExpression implements Boolea
public static BooleanExpression createOR(BooleanExpression lvalue, BooleanExpression rvalue) {
return new LogicExpression(lvalue, rvalue) {
- public Object evaluate(AMQMessage message) throws JMSException {
+ public Object evaluate(AMQMessage message) throws AMQException {
Boolean lv = (Boolean) left.evaluate(message);
// Can we do an OR shortcut??
@@ -56,7 +54,7 @@ public abstract class LogicExpression extends BinaryExpression implements Boolea
public static BooleanExpression createAND(BooleanExpression lvalue, BooleanExpression rvalue) {
return new LogicExpression(lvalue, rvalue) {
- public Object evaluate(AMQMessage message) throws JMSException {
+ public Object evaluate(AMQMessage message) throws AMQException {
Boolean lv = (Boolean) left.evaluate(message);
@@ -85,9 +83,9 @@ public abstract class LogicExpression extends BinaryExpression implements Boolea
super(left, right);
}
- abstract public Object evaluate(AMQMessage message) throws JMSException;
+ abstract public Object evaluate(AMQMessage message) throws AMQException;
- public boolean matches(AMQMessage message) throws JMSException {
+ public boolean matches(AMQMessage message) throws AMQException {
Object object = evaluate(message);
return object!=null && object==Boolean.TRUE;
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/MessageFilter.java b/java/broker/src/main/java/org/apache/qpid/server/filter/MessageFilter.java
index b8ca75d209..f80b7941b5 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/filter/MessageFilter.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/filter/MessageFilter.java
@@ -21,10 +21,9 @@
package org.apache.qpid.server.filter;
import org.apache.qpid.server.queue.AMQMessage;
-
-import javax.jms.JMSException;
+import org.apache.qpid.AMQException;
public interface MessageFilter
{
- boolean matches(AMQMessage message) throws JMSException;
+ boolean matches(AMQMessage message) throws AMQException;
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/NoConsumerFilter.java b/java/broker/src/main/java/org/apache/qpid/server/filter/NoConsumerFilter.java
index 283d324ff6..47ca930d12 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/filter/NoConsumerFilter.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/filter/NoConsumerFilter.java
@@ -20,15 +20,9 @@
*/
package org.apache.qpid.server.filter;
-import org.apache.qpid.server.queue.AMQMessage;
-import org.apache.qpid.server.filter.jms.selector.SelectorParser;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.AMQInvalidSelectorException;
import org.apache.log4j.Logger;
-
-
-import javax.jms.InvalidSelectorException;
-import javax.jms.JMSException;
+import org.apache.qpid.AMQException;
+import org.apache.qpid.server.queue.AMQMessage;
public class NoConsumerFilter implements MessageFilter
{
@@ -36,7 +30,7 @@ public class NoConsumerFilter implements MessageFilter
public NoConsumerFilter() throws AMQException
- {
+ {
_logger.info("Created NoConsumerFilter");
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/PropertyExpression.java b/java/broker/src/main/java/org/apache/qpid/server/filter/PropertyExpression.java
index 02b07db93d..dfc80546ee 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/filter/PropertyExpression.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/filter/PropertyExpression.java
@@ -21,19 +21,12 @@ package org.apache.qpid.server.filter;
// Based on like named file from r450141 of the Apache ActiveMQ project <http://www.activemq.org/site/home.html>
//
-import java.io.IOException;
+//import java.io.IOException;
import java.util.HashMap;
-import javax.jms.DeliveryMode;
-import javax.jms.JMSException;
-
-//import org.apache.activemq.command.ActiveMQDestination;
-//import org.apache.activemq.command.Message;
-//import org.apache.activemq.command.TransactionId;
-//import org.apache.activemq.util.JMSExceptionSupport;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.framing.FieldTable;
import org.apache.qpid.server.queue.AMQMessage;
-import org.apache.qpid.server.message.jms.JMSMessage;
import org.apache.qpid.AMQException;
import org.apache.log4j.Logger;
@@ -44,41 +37,11 @@ import org.apache.log4j.Logger;
*/
public class PropertyExpression implements Expression
{
-
- interface SubExpression
- {
- public Object evaluate(AMQMessage message);
- }
-
- interface JMSExpression
- {
- public abstract Object evaluate(JMSMessage message);
- }
-
- static class SubJMSExpression implements SubExpression
- {
- JMSExpression _expression;
-
- SubJMSExpression(JMSExpression expression)
- {
- _expression = expression;
- }
-
-
- public Object evaluate(AMQMessage message)
- {
- JMSMessage msg = (JMSMessage) message.getDecodedMessage(AMQMessage.JMS_MESSAGE);
- if (msg != null)
- {
- return _expression.evaluate(msg);
- }
- else
- {
- return null;
- }
- }
- }
-
+ // Constants - defined the same as JMS
+ private static final int NON_PERSISTENT = 1;
+ private static final int PERSISTENT = 2;
+ private static final int DEFAULT_PRIORITY = 4;
+
private final static Logger _logger = org.apache.log4j.Logger.getLogger(PropertyExpression.class);
@@ -86,62 +49,43 @@ public class PropertyExpression implements Expression
static
{
- JMS_PROPERTY_EXPRESSIONS.put("JMSDestination", new SubJMSExpression(
- new JMSExpression()
+ JMS_PROPERTY_EXPRESSIONS.put("JMSDestination",
+ new Expression()
{
- public Object evaluate(JMSMessage message)
+ public Object evaluate(AMQMessage message)
{
- return message.getJMSDestination();
+ return message.getDestination();
}
}
- ));
-//
-// public Object evaluate(AMQMessage message)
-// {
-// //fixme
-//
-//
-//// AMQDestination dest = message.getOriginalDestination();
-//// if (dest == null)
-//// {
-//// dest = message.getDestination();
-//// }
-//// if (dest == null)
-//// {
-//// return null;
-//// }
-//// return dest.toString();
-// return "";
-// }
-// });
- JMS_PROPERTY_EXPRESSIONS.put("JMSReplyTo", new SubJMSExpression(
- new JMSExpression()
+ );
+ JMS_PROPERTY_EXPRESSIONS.put("JMSReplyTo",
+ new Expression()
{
- public Object evaluate(JMSMessage message)
+ public Object evaluate(AMQMessage message)
{
- return message.getJMSReplyTo();
+ return message.getReplyTo();
}
- })
+ }
);
- JMS_PROPERTY_EXPRESSIONS.put("JMSType", new SubJMSExpression(
- new JMSExpression()
+ JMS_PROPERTY_EXPRESSIONS.put("JMSType",
+ new Expression()
{
- public Object evaluate(JMSMessage message)
+ public Object evaluate(AMQMessage message)
{
- return message.getJMSType();
+ return message.getType();
}
}
- ));
+ );
- JMS_PROPERTY_EXPRESSIONS.put("JMSDeliveryMode", new SubJMSExpression(
- new JMSExpression()
+ JMS_PROPERTY_EXPRESSIONS.put("JMSDeliveryMode",
+ new Expression()
{
- public Object evaluate(JMSMessage message)
+ public Object evaluate(AMQMessage message)
{
try
{
- Integer mode = new Integer(message.getAMQMessage().isPersistent() ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT);
+ int mode = message.isPersistent() ? PERSISTENT : NON_PERSISTENT;
_logger.info("JMSDeliveryMode is :" + mode);
return mode;
}
@@ -150,83 +94,83 @@ public class PropertyExpression implements Expression
//shouldn't happen
}
- return DeliveryMode.NON_PERSISTENT;
+ return NON_PERSISTENT;
}
- }));
+ });
- JMS_PROPERTY_EXPRESSIONS.put("JMSPriority", new SubJMSExpression(
- new JMSExpression()
+ JMS_PROPERTY_EXPRESSIONS.put("JMSPriority",
+ new Expression()
{
- public Object evaluate(JMSMessage message)
+ public Object evaluate(AMQMessage message)
{
- return message.getJMSPriority();
+ return message.getPriority();
}
}
- ));
+ );
- JMS_PROPERTY_EXPRESSIONS.put("AMQMessageID", new SubJMSExpression(
- new JMSExpression()
+ JMS_PROPERTY_EXPRESSIONS.put("AMQMessageID",
+ new Expression()
{
- public Object evaluate(JMSMessage message)
+ public Object evaluate(AMQMessage message)
{
- return message.getAMQMessage().getMessageId();
+ return message.getMessageId();
}
}
- ));
+ );
- JMS_PROPERTY_EXPRESSIONS.put("JMSTimestamp", new SubJMSExpression(
- new JMSExpression()
+ JMS_PROPERTY_EXPRESSIONS.put("JMSTimestamp",
+ new Expression()
{
- public Object evaluate(JMSMessage message)
+ public Object evaluate(AMQMessage message)
{
- return message.getJMSTimestamp();
+ return message.getTimestamp();
}
}
- ));
+ );
- JMS_PROPERTY_EXPRESSIONS.put("JMSCorrelationID", new SubJMSExpression(
- new JMSExpression()
+ JMS_PROPERTY_EXPRESSIONS.put("JMSCorrelationID",
+ new Expression()
{
- public Object evaluate(JMSMessage message)
+ public Object evaluate(AMQMessage message)
{
- return message.getJMSCorrelationID();
+ return message.getCorrelationId();
}
}
- ));
+ );
- JMS_PROPERTY_EXPRESSIONS.put("JMSExpiration", new SubJMSExpression(
- new JMSExpression()
+ JMS_PROPERTY_EXPRESSIONS.put("JMSExpiration",
+ new Expression()
{
- public Object evaluate(JMSMessage message)
+ public Object evaluate(AMQMessage message)
{
- return message.getJMSExpiration();
+ return message.getExpiration();
}
}
- ));
+ );
- JMS_PROPERTY_EXPRESSIONS.put("JMSRedelivered", new SubJMSExpression(
- new JMSExpression()
+ JMS_PROPERTY_EXPRESSIONS.put("JMSRedelivered",
+ new Expression()
{
- public Object evaluate(JMSMessage message)
+ public Object evaluate(AMQMessage message)
{
- return message.getAMQMessage().isRedelivered();
+ return message.isRedelivered();
}
}
- ));
+ );
}
- private final String name;
- private final SubExpression jmsPropertyExpression;
+ private final AMQShortString name;
+ private final Expression jmsPropertyExpression;
- public PropertyExpression(String name)
+ public PropertyExpression(AMQShortString name)
{
this.name = name;
- jmsPropertyExpression = (SubExpression) JMS_PROPERTY_EXPRESSIONS.get(name);
+ jmsPropertyExpression = (Expression) JMS_PROPERTY_EXPRESSIONS.get(name);
}
- public Object evaluate(AMQMessage message) throws JMSException
+ public Object evaluate(AMQMessage message) throws AMQException
{
// try
// {
@@ -252,21 +196,21 @@ public class PropertyExpression implements Expression
}
// catch (IOException ioe)
// {
-// JMSException exception = new JMSException("Could not get property: " + name + " reason: " + ioe.getMessage());
+// AMQException exception = new AMQException("Could not get property: " + name + " reason: " + ioe.getMessage());
// exception.initCause(ioe);
// throw exception;
// }
// }
// catch (IOException e)
// {
-// JMSException exception = new JMSException(e.getMessage());
+// AMQException exception = new AMQException(e.getMessage());
// exception.initCause(e);
// throw exception;
// }
}
- public String getName()
+ public AMQShortString getName()
{
return name;
}
@@ -277,7 +221,7 @@ public class PropertyExpression implements Expression
*/
public String toString()
{
- return name;
+ return name.asString();
}
/**
diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/SimpleFilterManager.java b/java/broker/src/main/java/org/apache/qpid/server/filter/SimpleFilterManager.java
index dc2c2c0e6c..5821a84774 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/filter/SimpleFilterManager.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/filter/SimpleFilterManager.java
@@ -20,16 +20,15 @@
*/
package org.apache.qpid.server.filter;
+import org.apache.log4j.Logger;
import org.apache.qpid.server.queue.AMQMessage;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import org.apache.qpid.AMQException;
-import javax.jms.JMSException;
import java.util.concurrent.ConcurrentLinkedQueue;
public class SimpleFilterManager implements FilterManager
{
- private final Logger _logger = LoggerFactory.getLogger(SimpleFilterManager.class);
+ private final Logger _logger = Logger.getLogger(SimpleFilterManager.class);
private final ConcurrentLinkedQueue<MessageFilter> _filters;
@@ -60,10 +59,10 @@ public class SimpleFilterManager implements FilterManager
return false;
}
}
- catch (JMSException e)
+ catch (AMQException e)
{
//fixme
- e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
+ e.printStackTrace();
return false;
}
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/UnaryExpression.java b/java/broker/src/main/java/org/apache/qpid/server/filter/UnaryExpression.java
index 49ff147411..352a48b7ab 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/filter/UnaryExpression.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/filter/UnaryExpression.java
@@ -20,8 +20,8 @@ package org.apache.qpid.server.filter;
// Based on like named file from r450141 of the Apache ActiveMQ project <http://www.activemq.org/site/home.html>
//
+import org.apache.qpid.AMQException;
import org.apache.qpid.server.queue.AMQMessage;
-import org.apache.qpid.server.message.jms.JMSMessage;
import java.math.BigDecimal;
import java.util.Collection;
@@ -29,8 +29,6 @@ import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
-import javax.jms.JMSException;
-
/**
* An expression which performs an operation on two expression values
*
@@ -43,7 +41,8 @@ public abstract class UnaryExpression implements Expression {
public static Expression createNegate(Expression left) {
return new UnaryExpression(left) {
- public Object evaluate(AMQMessage message) throws JMSException {
+ public Object evaluate(AMQMessage message) throws AMQException
+ {
Object rvalue = right.evaluate(message);
if (rvalue == null) {
return null;
@@ -74,7 +73,7 @@ public abstract class UnaryExpression implements Expression {
final Collection inList = t;
return new BooleanUnaryExpression(right) {
- public Object evaluate(AMQMessage message) throws JMSException {
+ public Object evaluate(AMQMessage message) throws AMQException {
Object rvalue = right.evaluate(message);
if (rvalue == null) {
@@ -126,7 +125,7 @@ public abstract class UnaryExpression implements Expression {
super(left);
}
- public boolean matches(AMQMessage message) throws JMSException {
+ public boolean matches(AMQMessage message) throws AMQException {
Object object = evaluate(message);
return object!=null && object==Boolean.TRUE;
}
@@ -135,7 +134,7 @@ public abstract class UnaryExpression implements Expression {
public static BooleanExpression createNOT(BooleanExpression left) {
return new BooleanUnaryExpression(left) {
- public Object evaluate(AMQMessage message) throws JMSException {
+ public Object evaluate(AMQMessage message) throws AMQException {
Boolean lvalue = (Boolean) right.evaluate(message);
if (lvalue == null) {
return null;
@@ -159,7 +158,7 @@ public abstract class UnaryExpression implements Expression {
public static BooleanExpression createBooleanCast(Expression left) {
return new BooleanUnaryExpression(left) {
- public Object evaluate(AMQMessage message) throws JMSException {
+ public Object evaluate(AMQMessage message) throws AMQException {
Object rvalue = right.evaluate(message);
if (rvalue == null)
return null;
diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/XPathExpression.java b/java/broker/src/main/java/org/apache/qpid/server/filter/XPathExpression.java
index ab952b6fea..c51f82ce68 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/filter/XPathExpression.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/filter/XPathExpression.java
@@ -20,18 +20,14 @@ package org.apache.qpid.server.filter;
// Based on like named file from r450141 of the Apache ActiveMQ project <http://www.activemq.org/site/home.html>
//
-import java.io.IOException;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-
-import javax.jms.JMSException;
-
-//import org.apache.activemq.command.Message;
-//import org.apache.activemq.util.JMSExceptionSupport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.apache.qpid.AMQException;
import org.apache.qpid.server.queue.AMQMessage;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+
/**
* Used to evaluate an XPath Expression in a JMS selector.
*/
@@ -75,7 +71,7 @@ public final class XPathExpression implements BooleanExpression {
private final XPathEvaluator evaluator;
static public interface XPathEvaluator {
- public boolean evaluate(AMQMessage message) throws JMSException;
+ public boolean evaluate(AMQMessage message) throws AMQException;
}
XPathExpression(String xpath) {
@@ -97,7 +93,7 @@ public final class XPathExpression implements BooleanExpression {
}
}
- public Object evaluate(AMQMessage message) throws JMSException {
+ public Object evaluate(AMQMessage message) throws AMQException {
// try {
//FIXME this is flow to disk work
// if( message.isDropped() )
@@ -120,9 +116,10 @@ public final class XPathExpression implements BooleanExpression {
/**
* @param message
* @return true if the expression evaluates to Boolean.TRUE.
- * @throws JMSException
+ * @throws AMQException
*/
- public boolean matches(AMQMessage message) throws JMSException {
+ public boolean matches(AMQMessage message) throws AMQException
+ {
Object object = evaluate(message);
return object!=null && object==Boolean.TRUE;
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/XQueryExpression.java b/java/broker/src/main/java/org/apache/qpid/server/filter/XQueryExpression.java
index 53764cbf75..f5debb607a 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/filter/XQueryExpression.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/filter/XQueryExpression.java
@@ -17,9 +17,9 @@
*/
package org.apache.qpid.server.filter;
+import org.apache.qpid.AMQException;
import org.apache.qpid.server.queue.AMQMessage;
-import javax.jms.JMSException;
//
// Based on like named file from r450141 of the Apache ActiveMQ project <http://www.activemq.org/site/home.html>
//
@@ -35,7 +35,7 @@ public final class XQueryExpression implements BooleanExpression {
this.xpath = xpath;
}
- public Object evaluate(AMQMessage message) throws JMSException {
+ public Object evaluate(AMQMessage message) throws AMQException {
return Boolean.FALSE;
}
@@ -46,9 +46,10 @@ public final class XQueryExpression implements BooleanExpression {
/**
* @param message
* @return true if the expression evaluates to Boolean.TRUE.
- * @throws JMSException
+ * @throws AMQException
*/
- public boolean matches(AMQMessage message) throws JMSException {
+ public boolean matches(AMQMessage message) throws AMQException
+ {
Object object = evaluate(message);
return object!=null && object==Boolean.TRUE;
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/XalanXPathEvaluator.java b/java/broker/src/main/java/org/apache/qpid/server/filter/XalanXPathEvaluator.java
index 4b78fd18df..94f063aa95 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/filter/XalanXPathEvaluator.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/filter/XalanXPathEvaluator.java
@@ -21,23 +21,18 @@ package org.apache.qpid.server.filter;
// Based on like named file from r450141 of the Apache ActiveMQ project <http://www.activemq.org/site/home.html>
//
-import java.io.StringReader;
-import java.io.ByteArrayInputStream;
-
-import javax.jms.BytesMessage;
-import javax.jms.JMSException;
-import javax.jms.TextMessage;
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-
-//import org.apache.activemq.command.Message;
-//import org.apache.activemq.util.ByteArrayInputStream;
-import org.apache.xpath.CachedXPathAPI;
+import org.apache.qpid.AMQException;
import org.apache.qpid.server.queue.AMQMessage;
+import org.apache.xpath.CachedXPathAPI;
import org.w3c.dom.Document;
import org.w3c.dom.traversal.NodeIterator;
import org.xml.sax.InputSource;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import java.io.ByteArrayInputStream;
+import java.io.StringReader;
+
public class XalanXPathEvaluator implements XPathExpression.XPathEvaluator {
private final String xpath;
@@ -46,17 +41,24 @@ public class XalanXPathEvaluator implements XPathExpression.XPathEvaluator {
this.xpath = xpath;
}
- public boolean evaluate(AMQMessage m) throws JMSException {
+ public boolean evaluate(AMQMessage m) throws AMQException
+ {
+ // TODO - we would have to check the content type and then evaluate the content
+ // here... is this really a feature we wish to implement? - RobG
+ /*
+
if( m instanceof TextMessage ) {
String text = ((TextMessage)m).getText();
- return evaluate(text);
+ return evaluate(text);
} else if ( m instanceof BytesMessage ) {
BytesMessage bm = (BytesMessage) m;
byte data[] = new byte[(int) bm.getBodyLength()];
bm.readBytes(data);
return evaluate(data);
- }
+ }
+ */
return false;
+
}
private boolean evaluate(byte[] data) {
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelCloseHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelCloseHandler.java
index 4bde15b4b0..5d02027c0a 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelCloseHandler.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelCloseHandler.java
@@ -20,18 +20,15 @@
*/
package org.apache.qpid.server.handler;
-import org.apache.log4j.Logger;
import org.apache.qpid.AMQException;
import org.apache.qpid.framing.ChannelCloseBody;
-import org.apache.qpid.framing.AMQFrame;
-import org.apache.qpid.framing.ChannelCloseOkBody;
import org.apache.qpid.protocol.AMQMethodEvent;
-import org.apache.qpid.server.exchange.ExchangeRegistry;
import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.state.AMQStateManager;
import org.apache.qpid.server.state.StateAwareMethodListener;
+import org.apache.log4j.Logger;
+
public class ChannelCloseHandler implements StateAwareMethodListener<ChannelCloseBody>
{
private static final Logger _logger = Logger.getLogger(ChannelCloseHandler.class);
@@ -43,16 +40,14 @@ public class ChannelCloseHandler implements StateAwareMethodListener<ChannelClos
return _instance;
}
- private ChannelCloseHandler()
- {
- }
+ private ChannelCloseHandler() {}
- public void methodReceived(AMQProtocolSession protocolSession,
- AMQMethodEvent<ChannelCloseBody> evt) throws AMQException
+ public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<ChannelCloseBody> evt) throws AMQException
{
- ChannelCloseBody body = evt.getMethod();
+ AMQProtocolSession session = stateManager.getProtocolSession();
+ final ChannelCloseBody body = evt.getMethod();
_logger.info("Received channel close for id " + evt.getChannelId() + " citing class " +
body.classId + " and method " + body.methodId);
- protocolSession.closeChannelResponse(evt.getChannelId(), evt.getRequestId());
+ session.closeChannelResponse(evt.getChannelId(), evt.getRequestId());
}
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelCloseOkHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelCloseOkHandler.java
index 25d437093e..d90eb630d7 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelCloseOkHandler.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelCloseOkHandler.java
@@ -23,11 +23,10 @@ package org.apache.qpid.server.handler;
import org.apache.qpid.AMQException;
import org.apache.qpid.framing.ChannelCloseOkBody;
import org.apache.qpid.protocol.AMQMethodEvent;
-import org.apache.qpid.server.exchange.ExchangeRegistry;
import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.state.AMQStateManager;
import org.apache.qpid.server.state.StateAwareMethodListener;
+
import org.apache.log4j.Logger;
public class ChannelCloseOkHandler implements StateAwareMethodListener<ChannelCloseOkBody>
@@ -41,14 +40,12 @@ public class ChannelCloseOkHandler implements StateAwareMethodListener<ChannelCl
return _instance;
}
- private ChannelCloseOkHandler()
- {
- }
+ private ChannelCloseOkHandler() {}
- public void methodReceived(AMQProtocolSession protocolSession,
- AMQMethodEvent<ChannelCloseOkBody> evt) throws AMQException
+ public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<ChannelCloseOkBody> evt) throws AMQException
{
+ AMQProtocolSession session = stateManager.getProtocolSession();
_logger.info("Received channel-close-ok for channel-id " + evt.getChannelId());
- protocolSession.removeChannel(evt.getChannelId());
+ session.removeChannel(evt.getChannelId());
}
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelFlowHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelFlowHandler.java
index b9ecdeaa00..38919cbe96 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelFlowHandler.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelFlowHandler.java
@@ -20,18 +20,17 @@
*/
package org.apache.qpid.server.handler;
-import org.apache.log4j.Logger;
-import org.apache.qpid.protocol.AMQMethodEvent;
-import org.apache.qpid.server.state.AMQStateManager;
-import org.apache.qpid.server.state.StateAwareMethodListener;
-import org.apache.qpid.server.queue.QueueRegistry;
-import org.apache.qpid.server.exchange.ExchangeRegistry;
-import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.AMQChannel;
+import org.apache.qpid.AMQException;
import org.apache.qpid.framing.AMQMethodBody;
import org.apache.qpid.framing.ChannelFlowBody;
import org.apache.qpid.framing.ChannelFlowOkBody;
-import org.apache.qpid.AMQException;
+import org.apache.qpid.protocol.AMQMethodEvent;
+import org.apache.qpid.server.AMQChannel;
+import org.apache.qpid.server.protocol.AMQProtocolSession;
+import org.apache.qpid.server.state.AMQStateManager;
+import org.apache.qpid.server.state.StateAwareMethodListener;
+
+import org.apache.log4j.Logger;
public class ChannelFlowHandler implements StateAwareMethodListener<ChannelFlowBody>
{
@@ -44,24 +43,21 @@ public class ChannelFlowHandler implements StateAwareMethodListener<ChannelFlowB
return _instance;
}
- private ChannelFlowHandler()
- {
- }
+ private ChannelFlowHandler() {}
- public void methodReceived(AMQProtocolSession protocolSession,
- AMQMethodEvent<ChannelFlowBody> evt) throws AMQException
+ public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<ChannelFlowBody> evt) throws AMQException
{
- ChannelFlowBody body = evt.getMethod();
-
- AMQChannel channel = protocolSession.getChannel(evt.getChannelId());
+ AMQProtocolSession session = stateManager.getProtocolSession();
+ final ChannelFlowBody body = evt.getMethod();
+ AMQChannel channel = session.getChannel(evt.getChannelId());
channel.setSuspended(!body.active);
_logger.debug("Channel.Flow for channel " + evt.getChannelId() + ", active=" + body.active);
// Be aware of possible changes to parameter order as versions change.
AMQMethodBody response = ChannelFlowOkBody.createMethodBody(
- protocolSession.getMajor(), // AMQP major version
- protocolSession.getMinor(), // AMQP minor version
+ session.getProtocolMajorVersion(), // AMQP major version
+ session.getProtocolMinorVersion(), // AMQP minor version
body.active); // active
- protocolSession.writeResponse(evt, response);
+ session.writeResponse(evt, response);
}
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelOpenHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelOpenHandler.java
index 6405c89774..f030ae643d 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelOpenHandler.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelOpenHandler.java
@@ -26,16 +26,17 @@ import org.apache.qpid.framing.ChannelOpenBody;
import org.apache.qpid.framing.ChannelOpenOkBody;
import org.apache.qpid.protocol.AMQMethodEvent;
import org.apache.qpid.server.AMQChannel;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.server.registry.IApplicationRegistry;
-import org.apache.qpid.server.exchange.ExchangeRegistry;
import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.state.AMQStateManager;
import org.apache.qpid.server.state.StateAwareMethodListener;
+import org.apache.qpid.server.virtualhost.VirtualHost;
+
+//import org.apache.log4j.Logger;
public class ChannelOpenHandler implements StateAwareMethodListener<ChannelOpenBody>
{
+ //private static final Logger _logger = Logger.getLogger(ChannelOpenHandler.class);
+
private static ChannelOpenHandler _instance = new ChannelOpenHandler();
public static ChannelOpenHandler getInstance()
@@ -43,19 +44,18 @@ public class ChannelOpenHandler implements StateAwareMethodListener<ChannelOpenB
return _instance;
}
- private ChannelOpenHandler()
- {
- }
+ private ChannelOpenHandler() {}
- public void methodReceived(AMQProtocolSession protocolSession,
- AMQMethodEvent<ChannelOpenBody> evt) throws AMQException
+ public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<ChannelOpenBody> evt) throws AMQException
{
+ AMQProtocolSession session = stateManager.getProtocolSession();
+ VirtualHost virtualHost = session.getVirtualHost();
// Be aware of possible changes to parameter order as versions change.
// XXX: Client id
AMQMethodBody response = ChannelOpenOkBody.createMethodBody(
- protocolSession.getMajor(), // AMQP major version
- protocolSession.getMinor(), // AMQP minor version
+ session.getProtocolMajorVersion(), // AMQP major version
+ session.getProtocolMinorVersion(), // AMQP minor version
"XXX".getBytes());
- protocolSession.writeResponse(evt, response);
+ session.writeResponse(evt, response);
}
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionCloseMethodHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionCloseMethodHandler.java
index b47bb0ff34..a49562a5aa 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionCloseMethodHandler.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionCloseMethodHandler.java
@@ -20,16 +20,14 @@
*/
package org.apache.qpid.server.handler;
+import org.apache.qpid.AMQException;
import org.apache.qpid.framing.ConnectionCloseBody;
import org.apache.qpid.framing.AMQFrame;
-import org.apache.qpid.framing.ConnectionCloseOkBody;
import org.apache.qpid.protocol.AMQMethodEvent;
-import org.apache.qpid.server.state.StateAwareMethodListener;
-import org.apache.qpid.server.state.AMQStateManager;
-import org.apache.qpid.server.queue.QueueRegistry;
-import org.apache.qpid.server.exchange.ExchangeRegistry;
import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.AMQException;
+import org.apache.qpid.server.state.AMQStateManager;
+import org.apache.qpid.server.state.StateAwareMethodListener;
+
import org.apache.log4j.Logger;
public class ConnectionCloseMethodHandler implements StateAwareMethodListener<ConnectionCloseBody>
@@ -43,16 +41,14 @@ public class ConnectionCloseMethodHandler implements StateAwareMethodListener<C
return _instance;
}
- private ConnectionCloseMethodHandler()
- {
- }
+ private ConnectionCloseMethodHandler() {}
- public void methodReceived(AMQProtocolSession protocolSession,
- AMQMethodEvent<ConnectionCloseBody> evt) throws AMQException
+ public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<ConnectionCloseBody> evt) throws AMQException
{
+ AMQProtocolSession session = stateManager.getProtocolSession();
final ConnectionCloseBody body = evt.getMethod();
_logger.info("ConnectionClose received with reply code/reply text " + body.replyCode +
- "/" + body.replyText + " for " + protocolSession);
- protocolSession.closeSessionResponse(evt.getRequestId());
+ "/" + body.replyText + " for " + session);
+ session.closeSessionResponse(evt.getRequestId());
}
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionCloseOkMethodHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionCloseOkMethodHandler.java
index 941c1b7e76..9743ff713b 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionCloseOkMethodHandler.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionCloseOkMethodHandler.java
@@ -23,12 +23,10 @@ package org.apache.qpid.server.handler;
import org.apache.qpid.AMQException;
import org.apache.qpid.framing.ConnectionCloseOkBody;
import org.apache.qpid.protocol.AMQMethodEvent;
-import org.apache.qpid.server.exchange.ExchangeRegistry;
import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.state.AMQStateManager;
import org.apache.qpid.server.state.StateAwareMethodListener;
-import org.apache.qpid.server.state.AMQState;
+
import org.apache.log4j.Logger;
public class ConnectionCloseOkMethodHandler implements StateAwareMethodListener<ConnectionCloseOkBody>
@@ -42,14 +40,12 @@ public class ConnectionCloseOkMethodHandler implements StateAwareMethodListener<
return _instance;
}
- private ConnectionCloseOkMethodHandler()
- {
- }
+ private ConnectionCloseOkMethodHandler() {}
- public void methodReceived(AMQProtocolSession protocolSession,
- AMQMethodEvent<ConnectionCloseOkBody> evt) throws AMQException
+ public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<ConnectionCloseOkBody> evt) throws AMQException
{
+ AMQProtocolSession session = stateManager.getProtocolSession();
_logger.info("Received Connection-close-ok");
- protocolSession.closeSession();
+ session.closeSession();
}
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionOpenMethodHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionOpenMethodHandler.java
index a0105005b9..a29552de03 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionOpenMethodHandler.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionOpenMethodHandler.java
@@ -22,18 +22,23 @@ package org.apache.qpid.server.handler;
import org.apache.qpid.AMQException;
import org.apache.qpid.framing.AMQMethodBody;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.framing.ConnectionOpenBody;
import org.apache.qpid.framing.ConnectionOpenOkBody;
+import org.apache.qpid.protocol.AMQConstant;
import org.apache.qpid.protocol.AMQMethodEvent;
-import org.apache.qpid.server.exchange.ExchangeRegistry;
import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.state.AMQState;
import org.apache.qpid.server.state.AMQStateManager;
import org.apache.qpid.server.state.StateAwareMethodListener;
+import org.apache.qpid.server.virtualhost.VirtualHost;
+
+//import org.apache.log4j.Logger;
public class ConnectionOpenMethodHandler implements StateAwareMethodListener<ConnectionOpenBody>
{
+ //private static final Logger _logger = Logger.getLogger(ConnectionOpenMethodHandler.class);
+
private static ConnectionOpenMethodHandler _instance = new ConnectionOpenMethodHandler();
public static ConnectionOpenMethodHandler getInstance()
@@ -41,32 +46,50 @@ public class ConnectionOpenMethodHandler implements StateAwareMethodListener<Con
return _instance;
}
- private ConnectionOpenMethodHandler()
- {
- }
+ private ConnectionOpenMethodHandler() {}
- private static String generateClientID()
+ private static AMQShortString generateClientID()
{
- return Long.toString(System.currentTimeMillis());
+ return new AMQShortString(Long.toString(System.currentTimeMillis()));
}
- public void methodReceived(AMQProtocolSession protocolSession,
- AMQMethodEvent<ConnectionOpenBody> evt) throws AMQException
+ public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<ConnectionOpenBody> evt) throws AMQException
{
- ConnectionOpenBody body = evt.getMethod();
+ AMQProtocolSession session = stateManager.getProtocolSession();
+ final ConnectionOpenBody body = evt.getMethod();
+
+ //ignore leading '/'
+ String virtualHostName;
+ if((body.virtualHost != null) && body.virtualHost.charAt(0) == '/')
+ {
+ virtualHostName = new StringBuilder(body.virtualHost.subSequence(1,body.virtualHost.length())).toString();
+ }
+ else
+ {
+ virtualHostName = String.valueOf(body.virtualHost);
+ }
+
+ VirtualHost virtualHost = stateManager.getVirtualHostRegistry().getVirtualHost(virtualHostName);
+
+ if(virtualHost == null)
+ {
+ throw body.getConnectionException(AMQConstant.NOT_FOUND.getCode(), "Unknown virtual host: " + virtualHostName);
+ }
+
+ session.setVirtualHost( virtualHost );
- //todo //FIXME The virtual host must be validated by the server for the connection to open-ok
// See Spec (0.8.2). Section 3.1.2 Virtual Hosts
- if (protocolSession.getContextKey() == null)
+ if (session.getContextKey() == null)
{
- protocolSession.setContextKey(generateClientID());
+ session.setContextKey(generateClientID());
}
+
// Be aware of possible changes to parameter order as versions change.
AMQMethodBody response = ConnectionOpenOkBody.createMethodBody(
- protocolSession.getMajor(), // AMQP major version
- protocolSession.getMinor(), // AMQP minor version
+ session.getProtocolMajorVersion(), // AMQP major version
+ session.getProtocolMinorVersion(), // AMQP minor version
body.virtualHost); // knownHosts
- protocolSession.getStateManager().changeState(AMQState.CONNECTION_OPEN);
- protocolSession.writeResponse(evt, response);
+ session.getStateManager().changeState(AMQState.CONNECTION_OPEN);
+ session.writeResponse(evt, response);
}
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionSecureOkMethodHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionSecureOkMethodHandler.java
index d7c927110a..0e94886698 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionSecureOkMethodHandler.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionSecureOkMethodHandler.java
@@ -21,19 +21,22 @@
package org.apache.qpid.server.handler;
import org.apache.qpid.AMQException;
+import org.apache.qpid.framing.AMQMethodBody;
+import org.apache.qpid.framing.ConnectionSecureBody;
+import org.apache.qpid.framing.ConnectionSecureOkBody;
+import org.apache.qpid.framing.ConnectionTuneBody;
+import org.apache.qpid.protocol.AMQMethodEvent;
import org.apache.qpid.protocol.AMQConstant;
-import org.apache.qpid.framing.*;
import org.apache.qpid.protocol.AMQMethodEvent;
-import org.apache.qpid.server.exchange.ExchangeRegistry;
import org.apache.qpid.server.protocol.AMQProtocolSession;
import org.apache.qpid.server.protocol.HeartbeatConfig;
-import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.state.AMQState;
import org.apache.qpid.server.state.AMQStateManager;
import org.apache.qpid.server.state.StateAwareMethodListener;
+import org.apache.qpid.server.registry.ApplicationRegistry;
import org.apache.qpid.server.security.auth.AuthenticationManager;
import org.apache.qpid.server.security.auth.AuthenticationResult;
-import org.apache.qpid.server.registry.ApplicationRegistry;
+
import org.apache.log4j.Logger;
import javax.security.sasl.SaslServer;
@@ -50,35 +53,34 @@ public class ConnectionSecureOkMethodHandler implements StateAwareMethodListener
return _instance;
}
- private ConnectionSecureOkMethodHandler()
- {
- }
+ private ConnectionSecureOkMethodHandler() {}
- public void methodReceived(AMQProtocolSession protocolSession,
- AMQMethodEvent<ConnectionSecureOkBody> evt) throws AMQException
+ public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<ConnectionSecureOkBody> evt) throws AMQException
{
- ConnectionSecureOkBody body = evt.getMethod();
+ AMQProtocolSession session = stateManager.getProtocolSession();
+ final ConnectionSecureOkBody body = evt.getMethod();
AuthenticationManager authMgr = ApplicationRegistry.getInstance().getAuthenticationManager();
- SaslServer ss = protocolSession.getSaslServer();
+ SaslServer ss = session.getSaslServer();
if (ss == null)
{
throw new AMQException("No SASL context set up in session");
}
AuthenticationResult authResult = authMgr.authenticate(ss, body.response);
- AMQStateManager stateManager = protocolSession.getStateManager();
- byte major = protocolSession.getMajor();
- byte minor = protocolSession.getMinor();
+ byte major = session.getProtocolMajorVersion();
+ byte minor = session.getProtocolMinorVersion();
switch (authResult.status)
{
case ERROR:
// Can't do this as we violate protocol. Need to send Close
// throw new AMQException(AMQConstant.NOT_ALLOWED.getCode(), AMQConstant.NOT_ALLOWED.getName());
_logger.info("Authentication failed");
- disposeSaslServer(protocolSession);
- protocolSession.closeSessionRequest(AMQConstant.NOT_ALLOWED.getCode(),
+ stateManager.changeState(AMQState.CONNECTION_CLOSING);
+ // Be aware of possible changes to parameter order as versions change.
+ session.closeSessionRequest(AMQConstant.NOT_ALLOWED.getCode(),
AMQConstant.NOT_ALLOWED.getName(), body.getClazz(), body.getMethod());
+ disposeSaslServer(session);
break;
case SUCCESS:
_logger.info("Connected as: " + ss.getAuthorizationID());
@@ -92,8 +94,8 @@ public class ConnectionSecureOkMethodHandler implements StateAwareMethodListener
Integer.MAX_VALUE, // channelMax
ConnectionStartOkMethodHandler.getConfiguredFrameSize(), // frameMax
HeartbeatConfig.getInstance().getDelay()); // heartbeat
- protocolSession.writeResponse(evt, tune);
- disposeSaslServer(protocolSession);
+ session.writeResponse(evt, tune);
+ disposeSaslServer(session);
break;
case CONTINUE:
stateManager.changeState(AMQState.CONNECTION_NOT_AUTH);
@@ -101,7 +103,7 @@ public class ConnectionSecureOkMethodHandler implements StateAwareMethodListener
AMQMethodBody challenge = ConnectionSecureBody.createMethodBody(
major, minor, // AMQP version (major, minor)
authResult.challenge); // challenge
- protocolSession.writeResponse(evt, challenge);
+ session.writeResponse(evt, challenge);
}
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionStartOkMethodHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionStartOkMethodHandler.java
index 46ff76e264..104e4c33a1 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionStartOkMethodHandler.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionStartOkMethodHandler.java
@@ -20,18 +20,14 @@
*/
package org.apache.qpid.server.handler;
-import org.apache.log4j.Logger;
-import org.apache.commons.configuration.Configuration;
import org.apache.qpid.AMQException;
import org.apache.qpid.framing.AMQMethodBody;
import org.apache.qpid.framing.ConnectionSecureBody;
import org.apache.qpid.framing.ConnectionStartOkBody;
import org.apache.qpid.framing.ConnectionTuneBody;
import org.apache.qpid.protocol.AMQMethodEvent;
-import org.apache.qpid.server.exchange.ExchangeRegistry;
import org.apache.qpid.server.protocol.AMQProtocolSession;
import org.apache.qpid.server.protocol.HeartbeatConfig;
-import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.registry.ApplicationRegistry;
import org.apache.qpid.server.security.auth.AuthenticationManager;
import org.apache.qpid.server.security.auth.AuthenticationResult;
@@ -39,10 +35,12 @@ import org.apache.qpid.server.state.AMQState;
import org.apache.qpid.server.state.AMQStateManager;
import org.apache.qpid.server.state.StateAwareMethodListener;
+import org.apache.commons.configuration.Configuration;
+import org.apache.log4j.Logger;
+
import javax.security.sasl.SaslException;
import javax.security.sasl.SaslServer;
-
public class ConnectionStartOkMethodHandler implements StateAwareMethodListener<ConnectionStartOkBody>
{
private static final Logger _logger = Logger.getLogger(ConnectionStartOkMethodHandler.class);
@@ -56,13 +54,11 @@ public class ConnectionStartOkMethodHandler implements StateAwareMethodListener<
return _instance;
}
- private ConnectionStartOkMethodHandler()
- {
- }
+ private ConnectionStartOkMethodHandler() {}
- public void methodReceived(AMQProtocolSession protocolSession,
- AMQMethodEvent<ConnectionStartOkBody> evt) throws AMQException
+ public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<ConnectionStartOkBody> evt) throws AMQException
{
+ AMQProtocolSession session = stateManager.getProtocolSession();
final ConnectionStartOkBody body = evt.getMethod();
_logger.info("SASL Mechanism selected: " + body.mechanism);
_logger.info("Locale selected: " + body.locale);
@@ -72,18 +68,17 @@ public class ConnectionStartOkMethodHandler implements StateAwareMethodListener<
SaslServer ss = null;
try
{
- ss = authMgr.createSaslServer(body.mechanism, protocolSession.getLocalFQDN());
- protocolSession.setSaslServer(ss);
+ ss = authMgr.createSaslServer(String.valueOf(body.mechanism), session.getLocalFQDN());
+ session.setSaslServer(ss);
AuthenticationResult authResult = authMgr.authenticate(ss, body.response);
//save clientProperties
- if (protocolSession.getClientProperties() == null)
+ if (session.getClientProperties() == null)
{
- protocolSession.setClientProperties(body.clientProperties);
+ session.setClientProperties(body.clientProperties);
}
- AMQStateManager stateManager = protocolSession.getStateManager();
switch (authResult.status)
{
case ERROR:
@@ -94,26 +89,26 @@ public class ConnectionStartOkMethodHandler implements StateAwareMethodListener<
stateManager.changeState(AMQState.CONNECTION_NOT_TUNED);
// Be aware of possible changes to parameter order as versions change.
AMQMethodBody tune = ConnectionTuneBody.createMethodBody(
- protocolSession.getMajor(), // AMQP major version
- protocolSession.getMinor(), // AMQP minor version
+ session.getProtocolMajorVersion(), // AMQP major version
+ session.getProtocolMinorVersion(), // AMQP minor version
Integer.MAX_VALUE, // channelMax
getConfiguredFrameSize(), // frameMax
HeartbeatConfig.getInstance().getDelay()); // heartbeat
- protocolSession.writeRequest(evt.getChannelId(), tune, stateManager);
+ session.writeRequest(evt.getChannelId(), tune, stateManager);
break;
case CONTINUE:
stateManager.changeState(AMQState.CONNECTION_NOT_AUTH);
// Be aware of possible changes to parameter order as versions change.
AMQMethodBody challenge = ConnectionSecureBody.createMethodBody(
- protocolSession.getMajor(), // AMQP major version
- protocolSession.getMinor(), // AMQP minor version
+ session.getProtocolMajorVersion(), // AMQP major version
+ session.getProtocolMinorVersion(), // AMQP minor version
authResult.challenge); // challenge
- protocolSession.writeRequest(evt.getChannelId(), challenge, stateManager);
+ session.writeRequest(evt.getChannelId(), challenge, stateManager);
}
}
catch (SaslException e)
{
- disposeSaslServer(protocolSession);
+ disposeSaslServer(session);
throw new AMQException("SASL error: " + e, e);
}
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionTuneOkMethodHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionTuneOkMethodHandler.java
index 69bf103729..3d1f6d3944 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionTuneOkMethodHandler.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionTuneOkMethodHandler.java
@@ -20,17 +20,16 @@
*/
package org.apache.qpid.server.handler;
-import org.apache.log4j.Logger;
import org.apache.qpid.AMQException;
import org.apache.qpid.framing.ConnectionTuneOkBody;
import org.apache.qpid.protocol.AMQMethodEvent;
-import org.apache.qpid.server.exchange.ExchangeRegistry;
import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.state.AMQState;
import org.apache.qpid.server.state.AMQStateManager;
import org.apache.qpid.server.state.StateAwareMethodListener;
+import org.apache.log4j.Logger;
+
public class ConnectionTuneOkMethodHandler implements StateAwareMethodListener<ConnectionTuneOkBody>
{
private static final Logger _logger = Logger.getLogger(ConnectionTuneOkMethodHandler.class);
@@ -41,17 +40,19 @@ public class ConnectionTuneOkMethodHandler implements StateAwareMethodListener<C
{
return _instance;
}
+
+ private ConnectionTuneOkMethodHandler() {}
- public void methodReceived(AMQProtocolSession protocolSession,
- AMQMethodEvent<ConnectionTuneOkBody> evt) throws AMQException
+ public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<ConnectionTuneOkBody> evt) throws AMQException
{
- ConnectionTuneOkBody body = evt.getMethod();
+ AMQProtocolSession session = stateManager.getProtocolSession();
+ final ConnectionTuneOkBody body = evt.getMethod();
if (_logger.isDebugEnabled())
{
_logger.debug(body);
}
- protocolSession.getStateManager().changeState(AMQState.CONNECTION_NOT_OPENED);
- protocolSession.initHeartbeats(body.heartbeat);
- protocolSession.setFrameMax(body.getFrameMax());
+ stateManager.changeState(AMQState.CONNECTION_NOT_OPENED);
+ session.initHeartbeats(body.heartbeat);
+ session.setFrameMax(body.getFrameMax());
}
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeBoundHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeBoundHandler.java
index 22eadc40c9..8157651228 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeBoundHandler.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeBoundHandler.java
@@ -1,24 +1,28 @@
/*
*
- * Copyright (c) 2006 The Apache Software Foundation
- *
- * Licensed 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.
+ * 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.handler;
import org.apache.qpid.AMQException;
import org.apache.qpid.framing.AMQMethodBody;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.framing.ExchangeBoundBody;
import org.apache.qpid.framing.ExchangeBoundOkBody;
import org.apache.qpid.protocol.AMQMethodEvent;
@@ -29,13 +33,13 @@ import org.apache.qpid.server.queue.AMQQueue;
import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.state.AMQStateManager;
import org.apache.qpid.server.state.StateAwareMethodListener;
+import org.apache.qpid.server.virtualhost.VirtualHost;
+
+//import org.apache.log4j.Logger;
-/**
- * @author Apache Software Foundation
- */
public class ExchangeBoundHandler implements StateAwareMethodListener<ExchangeBoundBody>
{
- private static final ExchangeBoundHandler _instance = new ExchangeBoundHandler();
+ //private static final Logger _logger = Logger.getLogger(ExchangeBoundHandler.class);
public static final int OK = 0;
@@ -51,39 +55,42 @@ public class ExchangeBoundHandler implements StateAwareMethodListener<ExchangeBo
public static final int SPECIFIC_QUEUE_NOT_BOUND_WITH_RK = 6;
+ private static final ExchangeBoundHandler _instance = new ExchangeBoundHandler();
+
public static ExchangeBoundHandler getInstance()
{
return _instance;
}
- private ExchangeBoundHandler()
- {
- }
+ private ExchangeBoundHandler() {}
- public void methodReceived(AMQProtocolSession protocolSession,
- AMQMethodEvent<ExchangeBoundBody> evt) throws AMQException
+ public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<ExchangeBoundBody> evt) throws AMQException
{
- byte major = protocolSession.getMajor();
- byte minor = protocolSession.getMinor();
-
- ExchangeBoundBody body = evt.getMethod();
+ AMQProtocolSession session = stateManager.getProtocolSession();
+ final ExchangeBoundBody body = evt.getMethod();
+ VirtualHost virtualHost = session.getVirtualHost();
+ QueueRegistry queueRegistry = virtualHost.getQueueRegistry();
- String exchangeName = body.exchange;
- String queueName = body.queue;
- String routingKey = body.routingKey;
+ byte major = session.getProtocolMajorVersion();
+ byte minor = session.getProtocolMinorVersion();
+
+ AMQShortString exchangeName = body.exchange;
+ AMQShortString queueName = body.queue;
+ AMQShortString routingKey = body.routingKey;
if (exchangeName == null)
{
throw new AMQException("Exchange exchange must not be null");
}
- Exchange exchange = protocolSession.getExchangeRegistry().getExchange(exchangeName);
+ Exchange exchange = virtualHost.getExchangeRegistry().getExchange(exchangeName);
AMQMethodBody response;
+
if (exchange == null)
{
// AMQP version change: Be aware of possible changes to parameter order as versions change.
response = ExchangeBoundOkBody.createMethodBody
(major, minor, // AMQP version (major, minor)
EXCHANGE_NOT_FOUND, // replyCode
- "Exchange " + exchangeName + " not found"); // replyText
+ new AMQShortString("Exchange " + exchangeName + " not found")); // replyText
}
else if (routingKey == null)
{
@@ -108,14 +115,14 @@ public class ExchangeBoundHandler implements StateAwareMethodListener<ExchangeBo
}
else
{
- AMQQueue queue = protocolSession.getQueueRegistry().getQueue(queueName);
+ AMQQueue queue = queueRegistry.getQueue(queueName);
if (queue == null)
{
// AMQP version change: Be aware of possible changes to parameter order as versions change.
response = ExchangeBoundOkBody.createMethodBody
(major, minor, // AMQP version (major, minor)
QUEUE_NOT_FOUND, // replyCode
- "Queue " + queueName + " not found"); // replyText
+ new AMQShortString("Queue " + queueName + " not found")); // replyText
}
else
{
@@ -133,21 +140,22 @@ public class ExchangeBoundHandler implements StateAwareMethodListener<ExchangeBo
response = ExchangeBoundOkBody.createMethodBody
(major, minor, // AMQP version (major, minor)
QUEUE_NOT_BOUND, // replyCode
- "Queue " + queueName + " not bound to exchange " + exchangeName); // replyText
+ new AMQShortString("Queue " + queueName + " not bound to exchange " +
+ exchangeName)); // replyText
}
}
}
}
else if (queueName != null)
{
- AMQQueue queue = protocolSession.getQueueRegistry().getQueue(queueName);
+ AMQQueue queue = queueRegistry.getQueue(queueName);
if (queue == null)
{
// AMQP version change: Be aware of possible changes to parameter order as versions change.
response = ExchangeBoundOkBody.createMethodBody
(major, minor, // AMQP version (major, minor)
QUEUE_NOT_FOUND, // replyCode
- "Queue " + queueName + " not found"); // replyText
+ new AMQShortString("Queue " + queueName + " not found")); // replyText
}
else
{
@@ -165,8 +173,8 @@ public class ExchangeBoundHandler implements StateAwareMethodListener<ExchangeBo
response = ExchangeBoundOkBody.createMethodBody
(major, minor, // AMQP version (major, minor)
SPECIFIC_QUEUE_NOT_BOUND_WITH_RK, // replyCode
- "Queue " + queueName + " not bound with routing key " +
- body.routingKey + " to exchange " + exchangeName); // replyText
+ new AMQShortString("Queue " + queueName + " not bound with routing key " +
+ body.routingKey + " to exchange " + exchangeName)); // replyText
}
}
}
@@ -186,10 +194,10 @@ public class ExchangeBoundHandler implements StateAwareMethodListener<ExchangeBo
response = ExchangeBoundOkBody.createMethodBody
(major, minor, // AMQP version (major, minor)
NO_QUEUE_BOUND_WITH_RK, // replyCode
- "No queue bound with routing key " + body.routingKey +
- " to exchange " + exchangeName); // replyText
+ new AMQShortString("No queue bound with routing key " + body.routingKey +
+ " to exchange " + exchangeName)); // replyText
}
}
- protocolSession.writeResponse(evt, response);
+ session.writeResponse(evt, response);
}
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeDeclareHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeDeclareHandler.java
index 99d0df82cd..7b129f0187 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeDeclareHandler.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeDeclareHandler.java
@@ -20,9 +20,8 @@
*/
package org.apache.qpid.server.handler;
-import org.apache.log4j.Logger;
-import org.apache.qpid.AMQException;
import org.apache.qpid.AMQConnectionException;
+import org.apache.qpid.AMQException;
import org.apache.qpid.AMQUnknownExchangeType;
import org.apache.qpid.framing.AMQMethodBody;
import org.apache.qpid.framing.ExchangeDeclareBody;
@@ -30,13 +29,14 @@ import org.apache.qpid.framing.ExchangeDeclareOkBody;
import org.apache.qpid.protocol.AMQConstant;
import org.apache.qpid.protocol.AMQMethodEvent;
import org.apache.qpid.server.exchange.Exchange;
-import org.apache.qpid.server.exchange.ExchangeRegistry;
import org.apache.qpid.server.exchange.ExchangeFactory;
+import org.apache.qpid.server.exchange.ExchangeRegistry;
import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.state.AMQStateManager;
import org.apache.qpid.server.state.StateAwareMethodListener;
-import org.apache.qpid.server.registry.ApplicationRegistry;
+import org.apache.qpid.server.virtualhost.VirtualHost;
+
+import org.apache.log4j.Logger;
public class ExchangeDeclareHandler implements StateAwareMethodListener<ExchangeDeclareBody>
{
@@ -49,26 +49,26 @@ public class ExchangeDeclareHandler implements StateAwareMethodListener<Exchange
return _instance;
}
- private final ExchangeFactory exchangeFactory;
-
- private ExchangeDeclareHandler()
- {
- exchangeFactory = ApplicationRegistry.getInstance().getExchangeFactory();
- }
+ private ExchangeDeclareHandler() {}
- public void methodReceived(AMQProtocolSession protocolSession,
- AMQMethodEvent<ExchangeDeclareBody> evt) throws AMQException
+ public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<ExchangeDeclareBody> evt) throws AMQException
{
+ AMQProtocolSession session = stateManager.getProtocolSession();
final ExchangeDeclareBody body = evt.getMethod();
+ VirtualHost virtualHost = session.getVirtualHost();
+ ExchangeRegistry exchangeRegistry = virtualHost.getExchangeRegistry();
+ ExchangeFactory exchangeFactory = virtualHost.getExchangeFactory();
+
if (_logger.isDebugEnabled())
{
_logger.debug("Request to declare exchange of type " + body.type + " with name " + body.exchange);
}
- ExchangeRegistry exchangeRegistry = protocolSession.getExchangeRegistry();
synchronized(exchangeRegistry)
{
Exchange exchange = exchangeRegistry.getExchange(body.exchange);
+
+
if (exchange == null)
{
if(body.passive && ((body.type == null) || body.type.length() ==0))
@@ -85,23 +85,24 @@ public class ExchangeDeclareHandler implements StateAwareMethodListener<Exchange
}
catch(AMQUnknownExchangeType e)
{
- throw body.getConnectionException(AMQConstant.COMMAND_INVALID.getCode(), "Unknown exchange type: " + body.type,e);
+ throw body.getConnectionException(AMQConstant.COMMAND_INVALID.getCode(), "Unknown exchange type: " + body.type, e);
}
}
}
else if (!exchange.getType().equals(body.type))
{
- throw new AMQConnectionException(AMQConstant.NOT_ALLOWED.getCode(), "Attempt to redeclare exchange: " + body.exchange + " of type " + exchange.getType() + " to " + body.type +".",body.getClazz(), body.getMethod(),body.getMajor(),body.getMinor());
+ throw new AMQConnectionException(AMQConstant.NOT_ALLOWED.getCode(), "Attempt to redeclare exchange: " + body.exchange +
+ " of type " + exchange.getType() + " to " + body.type +".",body.getClazz(), body.getMethod(),body.getMajor(),body.getMinor());
}
}
if(!body.nowait)
{
// Be aware of possible changes to parameter order as versions change.
AMQMethodBody response = ExchangeDeclareOkBody.createMethodBody(
- protocolSession.getMajor(), // AMQP major version
- protocolSession.getMinor()); // AMQP minor version
- protocolSession.writeResponse(evt, response);
+ session.getProtocolMajorVersion(), // AMQP major version
+ session.getProtocolMinorVersion()); // AMQP minor version
+ session.writeResponse(evt, response);
}
}
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeDeleteHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeDeleteHandler.java
index b9ba123c7e..1e1cf67a1b 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeDeleteHandler.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeDeleteHandler.java
@@ -21,19 +21,22 @@
package org.apache.qpid.server.handler;
import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQFrame;
import org.apache.qpid.framing.ExchangeDeleteBody;
import org.apache.qpid.framing.ExchangeDeleteOkBody;
import org.apache.qpid.protocol.AMQMethodEvent;
import org.apache.qpid.server.exchange.ExchangeInUseException;
import org.apache.qpid.server.exchange.ExchangeRegistry;
import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.state.AMQStateManager;
import org.apache.qpid.server.state.StateAwareMethodListener;
+import org.apache.qpid.server.virtualhost.VirtualHost;
+
+//import org.apache.log4j.Logger;
public class ExchangeDeleteHandler implements StateAwareMethodListener<ExchangeDeleteBody>
{
+ //private static final Logger _logger = Logger.getLogger(ExchangeDeleteHandler.class);
+
private static final ExchangeDeleteHandler _instance = new ExchangeDeleteHandler();
public static ExchangeDeleteHandler getInstance()
@@ -41,21 +44,22 @@ public class ExchangeDeleteHandler implements StateAwareMethodListener<ExchangeD
return _instance;
}
- private ExchangeDeleteHandler()
- {
- }
+ private ExchangeDeleteHandler() {}
- public void methodReceived(AMQProtocolSession protocolSession,
- AMQMethodEvent<ExchangeDeleteBody> evt) throws AMQException
+ public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<ExchangeDeleteBody> evt) throws AMQException
{
- ExchangeDeleteBody body = evt.getMethod();
+ AMQProtocolSession session = stateManager.getProtocolSession();
+ final ExchangeDeleteBody body = evt.getMethod();
+ VirtualHost virtualHost = session.getVirtualHost();
+ ExchangeRegistry exchangeRegistry = virtualHost.getExchangeRegistry();
+
try
{
- protocolSession.getExchangeRegistry().unregisterExchange(body.exchange, body.ifUnused);
+ exchangeRegistry.unregisterExchange(body.exchange, body.ifUnused);
// Be aware of possible changes to parameter order as versions change.
- protocolSession.writeResponse(evt, ExchangeDeleteOkBody.createMethodBody(
- protocolSession.getMajor(), // AMQP major version
- protocolSession.getMinor())); // AMQP minor version
+ session.writeResponse(evt, ExchangeDeleteOkBody.createMethodBody(
+ session.getProtocolMajorVersion(), // AMQP major version
+ session.getProtocolMinorVersion())); // AMQP minor version
}
catch (ExchangeInUseException e)
{
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/MessageAppendHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/MessageAppendHandler.java
index e9357b300a..547ae3cdca 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/MessageAppendHandler.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/handler/MessageAppendHandler.java
@@ -22,15 +22,19 @@ package org.apache.qpid.server.handler;
import org.apache.qpid.AMQException;
import org.apache.qpid.framing.MessageAppendBody;
+import org.apache.qpid.framing.MessageOkBody;
import org.apache.qpid.protocol.AMQMethodEvent;
-import org.apache.qpid.server.exchange.ExchangeRegistry;
+import org.apache.qpid.server.AMQChannel;
import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.state.AMQStateManager;
import org.apache.qpid.server.state.StateAwareMethodListener;
+//import org.apache.log4j.Logger;
+
public class MessageAppendHandler implements StateAwareMethodListener<MessageAppendBody>
{
+ //private static final Logger _logger = Logger.getLogger(MessageAppendHandler.class);
+
private static MessageAppendHandler _instance = new MessageAppendHandler();
public static MessageAppendHandler getInstance()
@@ -40,12 +44,14 @@ public class MessageAppendHandler implements StateAwareMethodListener<MessageApp
private MessageAppendHandler() {}
-
- public void methodReceived (AMQProtocolSession protocolSession,
- AMQMethodEvent<MessageAppendBody> evt)
- throws AMQException
+ public void methodReceived (AMQStateManager stateManager, AMQMethodEvent<MessageAppendBody> evt) throws AMQException
{
- // TODO
+ AMQProtocolSession session = stateManager.getProtocolSession();
+ AMQChannel channel = session.getChannel(evt.getChannelId());
+ channel.addMessageAppend(evt.getMethod());
+ session.writeResponse(evt, MessageOkBody.createMethodBody(
+ session.getProtocolMajorVersion(), // AMQP major version
+ session.getProtocolMinorVersion())); // AMQP minor version
}
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/MessageCancelHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/MessageCancelHandler.java
index 8f6a4d09f1..881b30f617 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/MessageCancelHandler.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/handler/MessageCancelHandler.java
@@ -26,14 +26,16 @@ import org.apache.qpid.framing.MessageCancelBody;
import org.apache.qpid.framing.MessageOkBody;
import org.apache.qpid.protocol.AMQMethodEvent;
import org.apache.qpid.server.AMQChannel;
-import org.apache.qpid.server.exchange.ExchangeRegistry;
import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.state.AMQStateManager;
import org.apache.qpid.server.state.StateAwareMethodListener;
+//import org.apache.log4j.Logger;
+
public class MessageCancelHandler implements StateAwareMethodListener<MessageCancelBody>
{
+ //private static final Logger _logger = Logger.getLogger(MessageCancelHandler.class);
+
private static MessageCancelHandler _instance = new MessageCancelHandler();
public static MessageCancelHandler getInstance()
@@ -42,21 +44,19 @@ public class MessageCancelHandler implements StateAwareMethodListener<MessageCan
}
private MessageCancelHandler() {}
-
-
- public void methodReceived (AMQProtocolSession protocolSession,
- AMQMethodEvent<MessageCancelBody> evt)
- throws AMQException
+
+ public void methodReceived (AMQStateManager stateManager, AMQMethodEvent<MessageCancelBody> evt) throws AMQException
{
- final AMQChannel channel = protocolSession.getChannel(evt.getChannelId());
+ AMQProtocolSession session = stateManager.getProtocolSession();
final MessageCancelBody body = evt.getMethod();
- channel.unsubscribeConsumer(protocolSession, body.destination);
+ final AMQChannel channel = session.getChannel(evt.getChannelId());
+ channel.unsubscribeConsumer(session, body.destination);
// Be aware of possible changes to parameter order as versions change.
final AMQMethodBody methodBody = MessageOkBody.createMethodBody(
- protocolSession.getMajor(), // AMQP major version
- protocolSession.getMinor()); // AMQP minor version
- protocolSession.writeResponse(evt, methodBody);
+ session.getProtocolMajorVersion(), // AMQP major version
+ session.getProtocolMinorVersion()); // AMQP minor version
+ session.writeResponse(evt, methodBody);
}
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/MessageCheckpointHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/MessageCheckpointHandler.java
index 59dd507ab8..164f264fd1 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/MessageCheckpointHandler.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/handler/MessageCheckpointHandler.java
@@ -23,14 +23,16 @@ package org.apache.qpid.server.handler;
import org.apache.qpid.AMQException;
import org.apache.qpid.framing.MessageCheckpointBody;
import org.apache.qpid.protocol.AMQMethodEvent;
-import org.apache.qpid.server.exchange.ExchangeRegistry;
import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.state.AMQStateManager;
import org.apache.qpid.server.state.StateAwareMethodListener;
+//import org.apache.log4j.Logger;
+
public class MessageCheckpointHandler implements StateAwareMethodListener<MessageCheckpointBody>
{
+ //private static final Logger _logger = Logger.getLogger(MessageCheckpointHandler.class);
+
private static MessageCheckpointHandler _instance = new MessageCheckpointHandler();
public static MessageCheckpointHandler getInstance()
@@ -40,10 +42,7 @@ public class MessageCheckpointHandler implements StateAwareMethodListener<Messag
private MessageCheckpointHandler() {}
-
- public void methodReceived (AMQProtocolSession protocolSession,
- AMQMethodEvent<MessageCheckpointBody> evt)
- throws AMQException
+ public void methodReceived (AMQStateManager stateManager, AMQMethodEvent<MessageCheckpointBody> evt) throws AMQException
{
// TODO
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/MessageCloseHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/MessageCloseHandler.java
index a53d435fff..921e78e17d 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/MessageCloseHandler.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/handler/MessageCloseHandler.java
@@ -22,15 +22,19 @@ package org.apache.qpid.server.handler;
import org.apache.qpid.AMQException;
import org.apache.qpid.framing.MessageCloseBody;
+import org.apache.qpid.framing.MessageOkBody;
import org.apache.qpid.protocol.AMQMethodEvent;
-import org.apache.qpid.server.exchange.ExchangeRegistry;
+import org.apache.qpid.server.AMQChannel;
import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.state.AMQStateManager;
import org.apache.qpid.server.state.StateAwareMethodListener;
+//import org.apache.log4j.Logger;
+
public class MessageCloseHandler implements StateAwareMethodListener<MessageCloseBody>
{
+ //private static final Logger _logger = Logger.getLogger(MessageCloseHandler.class);
+
private static MessageCloseHandler _instance = new MessageCloseHandler();
public static MessageCloseHandler getInstance()
@@ -39,13 +43,15 @@ public class MessageCloseHandler implements StateAwareMethodListener<MessageClos
}
private MessageCloseHandler() {}
-
-
- public void methodReceived (AMQProtocolSession protocolSession,
- AMQMethodEvent<MessageCloseBody> evt)
- throws AMQException
+
+ public void methodReceived (AMQStateManager stateManager, AMQMethodEvent<MessageCloseBody> evt) throws AMQException
{
- // TODO
+ AMQProtocolSession session = stateManager.getProtocolSession();
+ AMQChannel channel = session.getChannel(evt.getChannelId());
+ channel.addMessageClose(evt.getMethod());
+ session.writeResponse(evt, MessageOkBody.createMethodBody(
+ session.getProtocolMajorVersion(), // AMQP major version
+ session.getProtocolMinorVersion())); // AMQP minor version
}
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/MessageConsumeHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/MessageConsumeHandler.java
index 1d37456b8e..ce2f74b6fb 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/MessageConsumeHandler.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/handler/MessageConsumeHandler.java
@@ -20,9 +20,9 @@
*/
package org.apache.qpid.server.handler;
-import org.apache.log4j.Logger;
import org.apache.qpid.AMQException;
import org.apache.qpid.AMQInvalidSelectorException;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.framing.MessageConsumeBody;
import org.apache.qpid.framing.MessageOkBody;
import org.apache.qpid.protocol.AMQConstant;
@@ -32,7 +32,11 @@ import org.apache.qpid.server.ConsumerTagNotUniqueException;
import org.apache.qpid.server.protocol.AMQProtocolSession;
import org.apache.qpid.server.queue.AMQQueue;
import org.apache.qpid.server.queue.QueueRegistry;
+import org.apache.qpid.server.state.AMQStateManager;
import org.apache.qpid.server.state.StateAwareMethodListener;
+import org.apache.qpid.server.virtualhost.VirtualHost;
+
+import org.apache.log4j.Logger;
public class MessageConsumeHandler implements StateAwareMethodListener<MessageConsumeBody>
{
@@ -47,13 +51,13 @@ public class MessageConsumeHandler implements StateAwareMethodListener<MessageCo
private MessageConsumeHandler() {}
-
- public void methodReceived (AMQProtocolSession session,
- AMQMethodEvent<MessageConsumeBody> evt)
- throws AMQException
+ public void methodReceived (AMQStateManager stateManager, AMQMethodEvent<MessageConsumeBody> evt) throws AMQException
{
- MessageConsumeBody body = evt.getMethod();
+ AMQProtocolSession session = stateManager.getProtocolSession();
+ final MessageConsumeBody body = evt.getMethod();
final int channelId = evt.getChannelId();
+ VirtualHost virtualHost = session.getVirtualHost();
+ QueueRegistry queueRegistry = virtualHost.getQueueRegistry();
AMQChannel channel = session.getChannel(channelId);
if (channel == null)
@@ -63,32 +67,33 @@ public class MessageConsumeHandler implements StateAwareMethodListener<MessageCo
}
else
{
- AMQQueue queue = body.queue == null ? channel.getDefaultQueue() : session.getQueueRegistry().getQueue(body.queue);
+ AMQQueue queue = body.queue == null ? channel.getDefaultQueue() : queueRegistry.getQueue(body.queue);
if (queue == null)
{
_log.info("No queue for '" + body.queue + "'");
- if(body.queue!=null)
+ if(body.queue != null)
{
session.closeChannelRequest(evt.getChannelId(), AMQConstant.NOT_FOUND.getCode(),
- "No such queue, '" + body.queue + "'");
+ new AMQShortString("No such queue, '" + body.queue + "'"));
}
else
{
session.closeSessionRequest(AMQConstant.NOT_ALLOWED.getCode(),
- "No queue name provided, no default queue defined.", body.getClazz(), body.getMethod());
+ new AMQShortString("No queue name provided, no default queue defined."),
+ body.getClazz(), body.getMethod());
}
}
else
{
try
{
- /*AMQShort*/String destination = channel.subscribeToQueue
+ AMQShortString destination = channel.subscribeToQueue
(body.destination, queue, session, !body.noAck, /*XXX*/null, body.noLocal, body.exclusive);
// Be aware of possible changes to parameter order as versions change.
session.writeResponse(evt, MessageOkBody.createMethodBody(
- session.getMajor(), // AMQP major version
- session.getMinor())); // AMQP minor version
+ session.getProtocolMajorVersion(), // AMQP major version
+ session.getProtocolMinorVersion())); // AMQP minor version
//now allow queue to start async processing of any backlog of messages
queue.deliverAsync();
@@ -97,13 +102,14 @@ public class MessageConsumeHandler implements StateAwareMethodListener<MessageCo
{
_log.info("Closing connection due to invalid selector: " + ise.getMessage());
session.closeChannelRequest(evt.getChannelId(), AMQConstant.INVALID_SELECTOR.getCode(),
- ise.getMessage());
+ new AMQShortString(ise.getMessage()));
}
catch (ConsumerTagNotUniqueException e)
{
_log.info("Closing connection due to duplicate (non-unique) consumer tag: " + e.getMessage());
session.closeSessionRequest(AMQConstant.NOT_ALLOWED.getCode(),
- "Non-unique consumer tag, '" + body.destination + "'", body.getClazz(), body.getMethod());
+ new AMQShortString("Non-unique consumer tag, '" + body.destination + "'"),
+ body.getClazz(), body.getMethod());
}
catch (AMQQueue.ExistingExclusiveSubscription e)
{
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/MessageEmptyHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/MessageEmptyHandler.java
index 9b231722a2..eae39f9416 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/MessageEmptyHandler.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/handler/MessageEmptyHandler.java
@@ -23,14 +23,16 @@ package org.apache.qpid.server.handler;
import org.apache.qpid.AMQException;
import org.apache.qpid.framing.MessageEmptyBody;
import org.apache.qpid.protocol.AMQMethodEvent;
-import org.apache.qpid.server.exchange.ExchangeRegistry;
import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.state.AMQStateManager;
import org.apache.qpid.server.state.StateAwareMethodListener;
+//import org.apache.log4j.Logger;
+
public class MessageEmptyHandler implements StateAwareMethodListener<MessageEmptyBody>
{
+ //private static final Logger _logger = Logger.getLogger(MessageEmptyHandler.class);
+
private static MessageEmptyHandler _instance = new MessageEmptyHandler();
public static MessageEmptyHandler getInstance()
@@ -39,11 +41,8 @@ public class MessageEmptyHandler implements StateAwareMethodListener<MessageEmpt
}
private MessageEmptyHandler() {}
-
-
- public void methodReceived (AMQProtocolSession protocolSession,
- AMQMethodEvent<MessageEmptyBody> evt)
- throws AMQException
+
+ public void methodReceived (AMQStateManager stateManager, AMQMethodEvent<MessageEmptyBody> evt) throws AMQException
{
// TODO
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/MessageGetHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/MessageGetHandler.java
index 54cac39fb1..7ebcd6ab38 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/MessageGetHandler.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/handler/MessageGetHandler.java
@@ -21,16 +21,28 @@
package org.apache.qpid.server.handler;
import org.apache.qpid.AMQException;
+import org.apache.qpid.AMQInvalidSelectorException;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.framing.MessageGetBody;
+import org.apache.qpid.framing.MessageEmptyBody;
+import org.apache.qpid.framing.MessageOkBody;
+import org.apache.qpid.protocol.AMQConstant;
import org.apache.qpid.protocol.AMQMethodEvent;
-import org.apache.qpid.server.exchange.ExchangeRegistry;
+import org.apache.qpid.server.AMQChannel;
+import org.apache.qpid.server.ConsumerTagNotUniqueException;
import org.apache.qpid.server.protocol.AMQProtocolSession;
+import org.apache.qpid.server.queue.AMQQueue;
import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.state.AMQStateManager;
import org.apache.qpid.server.state.StateAwareMethodListener;
+import org.apache.qpid.server.virtualhost.VirtualHost;
+
+import org.apache.log4j.Logger;
public class MessageGetHandler implements StateAwareMethodListener<MessageGetBody>
{
+ private static final Logger _logger = Logger.getLogger(MessageGetHandler.class);
+
private static MessageGetHandler _instance = new MessageGetHandler();
public static MessageGetHandler getInstance()
@@ -40,11 +52,85 @@ public class MessageGetHandler implements StateAwareMethodListener<MessageGetBod
private MessageGetHandler() {}
- public void methodReceived (AMQProtocolSession protocolSession,
- AMQMethodEvent<MessageGetBody> evt)
- throws AMQException
+ public void methodReceived (AMQStateManager stateManager, AMQMethodEvent<MessageGetBody> evt) throws AMQException
{
- // TODO
+ AMQProtocolSession session = stateManager.getProtocolSession();
+ final MessageGetBody body = evt.getMethod();
+ final int channelId = evt.getChannelId();
+ VirtualHost virtualHost = session.getVirtualHost();
+ QueueRegistry queueRegistry = virtualHost.getQueueRegistry();
+
+ AMQChannel channel = session.getChannel(channelId);
+ if (channel == null)
+ {
+ _logger.error("Channel " + channelId + " not found");
+ // TODO: either alert or error that the
+ }
+ else
+ {
+ AMQQueue queue = body.queue == null ? channel.getDefaultQueue() : queueRegistry.getQueue(body.queue);
+
+ if (queue == null)
+ {
+ _logger.info("No queue for '" + body.queue + "'");
+ if(body.queue != null)
+ {
+ session.closeChannelRequest(evt.getChannelId(), AMQConstant.NOT_FOUND.getCode(),
+ new AMQShortString("No such queue, '" + body.queue + "'"));
+ }
+ else
+ {
+ session.closeSessionRequest(AMQConstant.NOT_ALLOWED.getCode(),
+ new AMQShortString("No queue name provided, no default queue defined."),
+ body.getClazz(), body.getMethod());
+ }
+ }
+ else
+ {
+ try
+ {
+ if(queue.performGet(session, channel, !body.noAck))
+ {
+ session.writeResponse(evt, MessageOkBody.createMethodBody(
+ session.getProtocolMajorVersion(), // AMQP major version
+ session.getProtocolMinorVersion())); // AMQP minor version
+ }
+ else
+ {
+ session.writeResponse(evt, MessageEmptyBody.createMethodBody(
+ session.getProtocolMajorVersion(), // AMQP major version
+ session.getProtocolMinorVersion())); // AMQP minor version
+ }
+ }
+ catch (AMQInvalidSelectorException ise)
+ {
+ _logger.info("Closing connection due to invalid selector: " + ise.getMessage());
+ session.closeChannelRequest(evt.getChannelId(), AMQConstant.INVALID_SELECTOR.getCode(),
+ new AMQShortString(ise.getMessage()));
+ }
+// catch (ConsumerTagNotUniqueException e)
+// {
+// _logger.info("Closing connection due to duplicate (non-unique) consumer tag: " + e.getMessage());
+// session.closeSessionRequest(AMQConstant.NOT_ALLOWED.getCode(),
+// new AMQShortString("Non-unique consumer tag, '" + body.destination + "'"),
+// body.getClazz(), body.getMethod());
+// }
+ catch (AMQQueue.ExistingExclusiveSubscription e)
+ {
+ throw body.getChannelException(AMQConstant.ACCESS_REFUSED.getCode(),
+ "Cannot subscribe to queue "
+ + queue.getName()
+ + " as it already has an existing exclusive consumer");
+ }
+ catch (AMQQueue.ExistingSubscriptionPreventsExclusive e)
+ {
+ throw body.getChannelException(AMQConstant.ACCESS_REFUSED.getCode(),
+ "Cannot subscribe to queue "
+ + queue.getName()
+ + " exclusively as it already has a consumer");
+ }
+ }
+ }
}
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/MessageOffsetHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/MessageOffsetHandler.java
index 687323a9c4..9b034f2062 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/MessageOffsetHandler.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/handler/MessageOffsetHandler.java
@@ -23,14 +23,16 @@ package org.apache.qpid.server.handler;
import org.apache.qpid.AMQException;
import org.apache.qpid.framing.MessageOffsetBody;
import org.apache.qpid.protocol.AMQMethodEvent;
-import org.apache.qpid.server.exchange.ExchangeRegistry;
import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.state.AMQStateManager;
import org.apache.qpid.server.state.StateAwareMethodListener;
+//import org.apache.log4j.Logger;
+
public class MessageOffsetHandler implements StateAwareMethodListener<MessageOffsetBody>
{
+ //private static final Logger _logger = Logger.getLogger(MessageOffsetHandler.class);
+
private static MessageOffsetHandler _instance = new MessageOffsetHandler();
public static MessageOffsetHandler getInstance()
@@ -40,10 +42,7 @@ public class MessageOffsetHandler implements StateAwareMethodListener<MessageOff
private MessageOffsetHandler() {}
-
- public void methodReceived (AMQProtocolSession protocolSession,
- AMQMethodEvent<MessageOffsetBody> evt)
- throws AMQException
+ public void methodReceived (AMQStateManager stateManager, AMQMethodEvent<MessageOffsetBody> evt) throws AMQException
{
// TODO
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/MessageOkHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/MessageOkHandler.java
index 20a7048ff1..c3e8ad186b 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/MessageOkHandler.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/handler/MessageOkHandler.java
@@ -23,14 +23,16 @@ package org.apache.qpid.server.handler;
import org.apache.qpid.AMQException;
import org.apache.qpid.framing.MessageOkBody;
import org.apache.qpid.protocol.AMQMethodEvent;
-import org.apache.qpid.server.exchange.ExchangeRegistry;
import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.state.AMQStateManager;
import org.apache.qpid.server.state.StateAwareMethodListener;
+//import org.apache.log4j.Logger;
+
public class MessageOkHandler implements StateAwareMethodListener<MessageOkBody>
{
+ //private static final Logger _logger = Logger.getLogger(MessageOkHandler.class);
+
private static MessageOkHandler _instance = new MessageOkHandler();
public static MessageOkHandler getInstance()
@@ -40,10 +42,7 @@ public class MessageOkHandler implements StateAwareMethodListener<MessageOkBody>
private MessageOkHandler() {}
-
- public void methodReceived (AMQProtocolSession protocolSession,
- AMQMethodEvent<MessageOkBody> evt)
- throws AMQException
+ public void methodReceived (AMQStateManager stateManager, AMQMethodEvent<MessageOkBody> evt) throws AMQException
{
// TODO
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/MessageOpenHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/MessageOpenHandler.java
index f048b6e78c..5ad295cedb 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/MessageOpenHandler.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/handler/MessageOpenHandler.java
@@ -22,15 +22,19 @@ package org.apache.qpid.server.handler;
import org.apache.qpid.AMQException;
import org.apache.qpid.framing.MessageOpenBody;
+import org.apache.qpid.framing.MessageOkBody;
import org.apache.qpid.protocol.AMQMethodEvent;
-import org.apache.qpid.server.exchange.ExchangeRegistry;
+import org.apache.qpid.server.AMQChannel;
import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.state.AMQStateManager;
import org.apache.qpid.server.state.StateAwareMethodListener;
+//import org.apache.log4j.Logger;
+
public class MessageOpenHandler implements StateAwareMethodListener<MessageOpenBody>
{
+ //private static final Logger _logger = Logger.getLogger(MessageOpenHandler.class);
+
private static MessageOpenHandler _instance = new MessageOpenHandler();
public static MessageOpenHandler getInstance()
@@ -39,13 +43,15 @@ public class MessageOpenHandler implements StateAwareMethodListener<MessageOpenB
}
private MessageOpenHandler() {}
-
-
- public void methodReceived (AMQProtocolSession protocolSession,
- AMQMethodEvent<MessageOpenBody> evt)
- throws AMQException
+
+ public void methodReceived (AMQStateManager stateManager, AMQMethodEvent<MessageOpenBody> evt) throws AMQException
{
- // TODO
+ AMQProtocolSession session = stateManager.getProtocolSession();
+ AMQChannel channel = session.getChannel(evt.getChannelId());
+ channel.addMessageOpen(evt.getMethod());
+ session.writeResponse(evt, MessageOkBody.createMethodBody(
+ session.getProtocolMajorVersion(), // AMQP major version
+ session.getProtocolMinorVersion())); // AMQP minor version
}
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/MessageQosHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/MessageQosHandler.java
index 745f740070..cab8a7d0ad 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/MessageQosHandler.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/handler/MessageQosHandler.java
@@ -24,14 +24,16 @@ import org.apache.qpid.AMQException;
import org.apache.qpid.framing.MessageQosBody;
import org.apache.qpid.framing.MessageOkBody;
import org.apache.qpid.protocol.AMQMethodEvent;
-import org.apache.qpid.server.exchange.ExchangeRegistry;
import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.state.AMQStateManager;
import org.apache.qpid.server.state.StateAwareMethodListener;
+//import org.apache.log4j.Logger;
+
public class MessageQosHandler implements StateAwareMethodListener<MessageQosBody>
{
+ //private static final Logger _logger = Logger.getLogger(MessageQosHandler.class);
+
private static MessageQosHandler _instance = new MessageQosHandler();
public static MessageQosHandler getInstance()
@@ -41,16 +43,14 @@ public class MessageQosHandler implements StateAwareMethodListener<MessageQosBod
private MessageQosHandler() {}
-
- public void methodReceived (AMQProtocolSession protocolSession,
- AMQMethodEvent<MessageQosBody> evt)
- throws AMQException
+ public void methodReceived (AMQStateManager stateManager, AMQMethodEvent<MessageQosBody> evt) throws AMQException
{
- protocolSession.getChannel(evt.getChannelId()).setPrefetchCount(evt.getMethod().prefetchCount);
+ AMQProtocolSession session = stateManager.getProtocolSession();
+ session.getChannel(evt.getChannelId()).setPrefetchCount(evt.getMethod().prefetchCount);
// Be aware of possible changes to parameter order as versions change.
- protocolSession.writeResponse(evt.getChannelId(), evt.getRequestId(), new MessageOkBody(
- protocolSession.getMajor(), // AMQP major version
- protocolSession.getMinor())); // AMQP minor version
+ session.writeResponse(evt.getChannelId(), evt.getRequestId(), MessageOkBody.createMethodBody(
+ session.getProtocolMajorVersion(), // AMQP major version
+ session.getProtocolMinorVersion())); // AMQP minor version
}
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/MessageRecoverHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/MessageRecoverHandler.java
index 3914d6d793..0dc41800b7 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/MessageRecoverHandler.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/handler/MessageRecoverHandler.java
@@ -20,19 +20,17 @@
*/
package org.apache.qpid.server.handler;
-import org.apache.log4j.Logger;
-
import org.apache.qpid.AMQException;
import org.apache.qpid.framing.MessageRecoverBody;
import org.apache.qpid.framing.MessageOkBody;
import org.apache.qpid.protocol.AMQMethodEvent;
import org.apache.qpid.server.AMQChannel;
-import org.apache.qpid.server.exchange.ExchangeRegistry;
import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.state.AMQStateManager;
import org.apache.qpid.server.state.StateAwareMethodListener;
+import org.apache.log4j.Logger;
+
public class MessageRecoverHandler implements StateAwareMethodListener<MessageRecoverBody>
{
private static final Logger _logger = Logger.getLogger(MessageRecoverHandler.class);
@@ -46,24 +44,28 @@ public class MessageRecoverHandler implements StateAwareMethodListener<MessageRe
private MessageRecoverHandler() {}
- public void methodReceived (AMQProtocolSession protocolSession,
- AMQMethodEvent<MessageRecoverBody> evt)
- throws AMQException
+ public void methodReceived (AMQStateManager stateManager, AMQMethodEvent<MessageRecoverBody> evt) throws AMQException
{
- _logger.debug("Recover received on protocol session " + protocolSession + " and channel " + evt.getChannelId());
- AMQChannel channel = protocolSession.getChannel(evt.getChannelId());
+ AMQProtocolSession session = stateManager.getProtocolSession();
+ AMQChannel channel = session.getChannel(evt.getChannelId());
+ _logger.debug("Recover received on protocol session " + session + " and channel " + evt.getChannelId());
if (channel == null)
{
throw new AMQException("Unknown channel " + evt.getChannelId());
}
MessageRecoverBody body = evt.getMethod();
- if (body.requeue) {
+ if (body.requeue)
+ {
channel.requeue();
- } else {
- channel.resend(protocolSession);
}
- MessageOkBody response = MessageOkBody.createMethodBody(protocolSession.getMajor(), protocolSession.getMinor());
- protocolSession.writeResponse(evt, response);
+ else
+ {
+ channel.resend(session, false);
+ }
+ MessageOkBody response = MessageOkBody.createMethodBody(
+ session.getProtocolMajorVersion(), // AMQP major version
+ session.getProtocolMinorVersion()); // AMQP minor version
+ session.writeResponse(evt, response);
}
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/MessageRejectHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/MessageRejectHandler.java
index 3ac1265fb4..9f89c77951 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/MessageRejectHandler.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/handler/MessageRejectHandler.java
@@ -23,14 +23,16 @@ package org.apache.qpid.server.handler;
import org.apache.qpid.AMQException;
import org.apache.qpid.framing.MessageRejectBody;
import org.apache.qpid.protocol.AMQMethodEvent;
-import org.apache.qpid.server.exchange.ExchangeRegistry;
import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.state.AMQStateManager;
import org.apache.qpid.server.state.StateAwareMethodListener;
+//import org.apache.log4j.Logger;
+
public class MessageRejectHandler implements StateAwareMethodListener<MessageRejectBody>
{
+ //private static final Logger _logger = Logger.getLogger(MessageRejectHandler.class);
+
private static MessageRejectHandler _instance = new MessageRejectHandler();
public static MessageRejectHandler getInstance()
@@ -39,11 +41,8 @@ public class MessageRejectHandler implements StateAwareMethodListener<MessageRej
}
private MessageRejectHandler() {}
-
-
- public void methodReceived (AMQProtocolSession protocolSession,
- AMQMethodEvent<MessageRejectBody> evt)
- throws AMQException
+
+ public void methodReceived (AMQStateManager stateManager, AMQMethodEvent<MessageRejectBody> evt) throws AMQException
{
// TODO
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/MessageResumeHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/MessageResumeHandler.java
index 95c1abb3da..dfaf5cb10d 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/MessageResumeHandler.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/handler/MessageResumeHandler.java
@@ -23,14 +23,16 @@ package org.apache.qpid.server.handler;
import org.apache.qpid.AMQException;
import org.apache.qpid.framing.MessageResumeBody;
import org.apache.qpid.protocol.AMQMethodEvent;
-import org.apache.qpid.server.exchange.ExchangeRegistry;
import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.state.AMQStateManager;
import org.apache.qpid.server.state.StateAwareMethodListener;
+//import org.apache.log4j.Logger;
+
public class MessageResumeHandler implements StateAwareMethodListener<MessageResumeBody>
{
+ //private static final Logger _logger = Logger.getLogger(MessageResumeHandler.class);
+
private static MessageResumeHandler _instance = new MessageResumeHandler();
public static MessageResumeHandler getInstance()
@@ -40,10 +42,7 @@ public class MessageResumeHandler implements StateAwareMethodListener<MessageRes
private MessageResumeHandler() {}
-
- public void methodReceived (AMQProtocolSession protocolSession,
- AMQMethodEvent<MessageResumeBody> evt)
- throws AMQException
+ public void methodReceived (AMQStateManager stateManager, AMQMethodEvent<MessageResumeBody> evt) throws AMQException
{
// TODO
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/MessageTransferHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/MessageTransferHandler.java
index fac68181d6..782909570d 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/MessageTransferHandler.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/handler/MessageTransferHandler.java
@@ -20,21 +20,21 @@
*/
package org.apache.qpid.server.handler;
-import org.apache.qpid.framing.MessageOkBody;
-import org.apache.log4j.Logger;
import org.apache.qpid.AMQException;
import org.apache.qpid.exchange.ExchangeDefaults;
-import org.apache.qpid.framing.AMQMethodBody;
-import org.apache.qpid.framing.ChannelCloseBody;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.framing.MessageTransferBody;
+import org.apache.qpid.framing.MessageOkBody;
import org.apache.qpid.protocol.AMQMethodEvent;
import org.apache.qpid.server.AMQChannel;
import org.apache.qpid.server.exchange.Exchange;
import org.apache.qpid.server.exchange.ExchangeRegistry;
import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.state.AMQStateManager;
import org.apache.qpid.server.state.StateAwareMethodListener;
+import org.apache.qpid.server.virtualhost.VirtualHost;
+
+import org.apache.log4j.Logger;
public class MessageTransferHandler implements StateAwareMethodListener<MessageTransferBody>
{
@@ -47,50 +47,41 @@ public class MessageTransferHandler implements StateAwareMethodListener<MessageT
return _instance;
}
- private static final String UNKNOWN_EXCHANGE_NAME = "Unknown exchange name";
-
private MessageTransferHandler() {}
- public void methodReceived (AMQProtocolSession protocolSession,
- AMQMethodEvent<MessageTransferBody> evt)
- throws AMQException
+ public void methodReceived (AMQStateManager stateManager, AMQMethodEvent<MessageTransferBody> evt) throws AMQException
{
+ AMQProtocolSession session = stateManager.getProtocolSession();
final MessageTransferBody body = evt.getMethod();
+ VirtualHost virtualHost = session.getVirtualHost();
+ ExchangeRegistry exchangeRegistry = virtualHost.getExchangeRegistry();
- if (_log.isDebugEnabled()) {
+ if (_log.isDebugEnabled())
+ {
_log.debug("Publish received on channel " + evt.getChannelId());
}
// TODO: check the delivery tag field details - is it unique across the broker or per subscriber?
- if (body.destination == null) {
+ if (body.destination == null)
+ {
body.destination = ExchangeDefaults.DIRECT_EXCHANGE_NAME;
}
- Exchange e = protocolSession.getExchangeRegistry().getExchange(body.destination);
+ Exchange e = exchangeRegistry.getExchange(body.destination);
// if the exchange does not exist we raise a channel exception
- if (e == null) {
-// protocolSession.closeChannel(evt.getChannelId());
-// // TODO: modify code gen to make getClazz and getMethod public methods rather than protected
-// // then we can remove the hardcoded 0,0
-// // AMQP version change: Hardwire the version to 0-9 (major=0, minor=9)
-// // TODO: Connect this to the session version obtained from ProtocolInitiation for this session.
-// // Be aware of possible changes to parameter order as versions change.
-// AMQMethodBody cf = ChannelCloseBody.createMethodBody
-// ((byte)0, (byte)9, // AMQP version (major, minor)
-// MessageTransferBody.getClazz((byte)0, (byte)9), // classId
-// MessageTransferBody.getMethod((byte)0, (byte)9), // methodId
-// 500, // replyCode
-// UNKNOWN_EXCHANGE_NAME); // replyText
-// protocolSession.writeRequest(evt.getChannelId(), cf, stateManager);
- protocolSession.closeChannelRequest(evt.getChannelId(), 500, UNKNOWN_EXCHANGE_NAME);
- } else {
+ if (e == null)
+ {
+ session.closeChannelRequest(evt.getChannelId(), 500, new AMQShortString("Unknown exchange name"));
+ }
+ else
+ {
// The partially populated BasicDeliver frame plus the received route body
// is stored in the channel. Once the final body frame has been received
// it is routed to the exchange.
- AMQChannel channel = protocolSession.getChannel(evt.getChannelId());
- channel.addMessageTransfer(body, protocolSession);
- protocolSession.writeResponse(evt, MessageOkBody.createMethodBody(
- protocolSession.getMajor(), // AMQP major version
- protocolSession.getMinor())); // AMQP minor version
+ AMQChannel channel = session.getChannel(evt.getChannelId());
+ channel.addMessageTransfer(body, session);
+ session.writeResponse(evt, MessageOkBody.createMethodBody(
+ session.getProtocolMajorVersion(), // AMQP major version
+ session.getProtocolMinorVersion())); // AMQP minor version
}
}
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/QueueBindHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/QueueBindHandler.java
index 94186e2f7e..1cef5b2b43 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/QueueBindHandler.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/handler/QueueBindHandler.java
@@ -20,7 +20,6 @@
*/
package org.apache.qpid.server.handler;
-import org.apache.log4j.Logger;
import org.apache.qpid.AMQException;
import org.apache.qpid.framing.AMQMethodBody;
import org.apache.qpid.framing.QueueBindBody;
@@ -34,6 +33,9 @@ import org.apache.qpid.server.queue.AMQQueue;
import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.state.AMQStateManager;
import org.apache.qpid.server.state.StateAwareMethodListener;
+import org.apache.qpid.server.virtualhost.VirtualHost;
+
+import org.apache.log4j.Logger;
public class QueueBindHandler implements StateAwareMethodListener<QueueBindBody>
{
@@ -46,18 +48,21 @@ public class QueueBindHandler implements StateAwareMethodListener<QueueBindBody>
return _instance;
}
- private QueueBindHandler()
- {
- }
+ private QueueBindHandler() {}
- public void methodReceived(AMQProtocolSession protocolSession,
- AMQMethodEvent<QueueBindBody> evt) throws AMQException
+ public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<QueueBindBody> evt) throws AMQException
{
+ AMQProtocolSession session = stateManager.getProtocolSession();
final QueueBindBody body = evt.getMethod();
+ VirtualHost virtualHost = session.getVirtualHost();
+ ExchangeRegistry exchangeRegistry = virtualHost.getExchangeRegistry();
+ QueueRegistry queueRegistry = virtualHost.getQueueRegistry();
+
+
final AMQQueue queue;
if (body.queue == null)
{
- queue = protocolSession.getChannel(evt.getChannelId()).getDefaultQueue();
+ queue = session.getChannel(evt.getChannelId()).getDefaultQueue();
if (queue == null)
{
throw new AMQException("No default queue defined on channel and queue was null");
@@ -69,14 +74,14 @@ public class QueueBindHandler implements StateAwareMethodListener<QueueBindBody>
}
else
{
- queue = protocolSession.getQueueRegistry().getQueue(body.queue);
+ queue = queueRegistry.getQueue(body.queue);
}
if (queue == null)
{
throw body.getChannelException(AMQConstant.NOT_FOUND.getCode(), "Queue " + body.queue + " does not exist.");
}
- final Exchange exch = protocolSession.getExchangeRegistry().getExchange(body.exchange);
+ final Exchange exch = exchangeRegistry.getExchange(body.exchange);
if (exch == null)
{
throw body.getChannelException(AMQConstant.NOT_FOUND.getCode(), "Exchange " + body.exchange + " does not exist.");
@@ -91,9 +96,9 @@ public class QueueBindHandler implements StateAwareMethodListener<QueueBindBody>
{
// Be aware of possible changes to parameter order as versions change.
final AMQMethodBody response = QueueBindOkBody.createMethodBody(
- protocolSession.getMajor(), // AMQP major version
- protocolSession.getMinor()); // AMQP minor version
- protocolSession.writeResponse(evt, response);
+ session.getProtocolMajorVersion(), // AMQP major version
+ session.getProtocolMinorVersion()); // AMQP minor version
+ session.writeResponse(evt, response);
}
}
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/QueueDeclareHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/QueueDeclareHandler.java
index c4a480530b..4ae80480aa 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/QueueDeclareHandler.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/handler/QueueDeclareHandler.java
@@ -20,24 +20,27 @@
*/
package org.apache.qpid.server.handler;
-import org.apache.log4j.Logger;
import org.apache.qpid.AMQException;
import org.apache.qpid.configuration.Configured;
+import org.apache.qpid.exchange.ExchangeDefaults;
import org.apache.qpid.framing.AMQMethodBody;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.framing.QueueDeclareBody;
import org.apache.qpid.framing.QueueDeclareOkBody;
import org.apache.qpid.protocol.AMQConstant;
import org.apache.qpid.protocol.AMQMethodEvent;
-import org.apache.qpid.server.exchange.ExchangeRegistry;
+import org.apache.qpid.server.configuration.Configurator;
import org.apache.qpid.server.exchange.Exchange;
+import org.apache.qpid.server.exchange.ExchangeRegistry;
import org.apache.qpid.server.protocol.AMQProtocolSession;
import org.apache.qpid.server.queue.AMQQueue;
import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.state.AMQStateManager;
import org.apache.qpid.server.state.StateAwareMethodListener;
-import org.apache.qpid.server.configuration.Configurator;
import org.apache.qpid.server.store.MessageStore;
-import org.apache.qpid.server.registry.ApplicationRegistry;
+import org.apache.qpid.server.virtualhost.VirtualHost;
+
+import org.apache.log4j.Logger;
import java.text.MessageFormat;
import java.util.concurrent.atomic.AtomicInteger;
@@ -58,28 +61,27 @@ public class QueueDeclareHandler implements StateAwareMethodListener<QueueDeclar
private final AtomicInteger _counter = new AtomicInteger();
- private final MessageStore _store;
-
protected QueueDeclareHandler()
{
Configurator.configure(this);
- _store = ApplicationRegistry.getInstance().getMessageStore();
}
- public void methodReceived(AMQProtocolSession protocolSession,
- AMQMethodEvent<QueueDeclareBody> evt) throws AMQException
+ public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<QueueDeclareBody> evt) throws AMQException
{
- QueueDeclareBody body = evt.getMethod();
+ AMQProtocolSession session = stateManager.getProtocolSession();
+ final QueueDeclareBody body = evt.getMethod();
+ VirtualHost virtualHost = session.getVirtualHost();
+ ExchangeRegistry exchangeRegistry = virtualHost.getExchangeRegistry();
+ QueueRegistry queueRegistry = virtualHost.getQueueRegistry();
+ MessageStore store = virtualHost.getMessageStore();
// if we aren't given a queue name, we create one which we return to the client
if (body.queue == null)
{
body.queue = createName();
}
- //TODO: do we need to check that the queue already exists with exactly the same "configuration"?
AMQQueue queue = null;
- QueueRegistry queueRegistry = protocolSession.getQueueRegistry();
synchronized (queueRegistry)
{
if ((queue = queueRegistry.getQueue(body.queue)) == null)
@@ -92,22 +94,22 @@ public class QueueDeclareHandler implements StateAwareMethodListener<QueueDeclar
}
else
{
- queue = createQueue(body, queueRegistry, protocolSession);
+ queue = createQueue(body, virtualHost, session);
if (queue.isDurable() && !queue.isAutoDelete())
{
- _store.createQueue(queue);
+ store.createQueue(queue);
}
queueRegistry.registerQueue(queue);
if (autoRegister)
{
- Exchange defaultExchange = protocolSession.getExchangeRegistry().getExchange("amq.direct");
+ Exchange defaultExchange = exchangeRegistry.getExchange(ExchangeDefaults.DIRECT_EXCHANGE_NAME);
defaultExchange.registerQueue(body.queue, queue, null);
queue.bind(body.queue, defaultExchange);
_log.info("Queue " + body.queue + " bound to default exchange");
}
}
}
- else if(queue.getOwner() != null && !protocolSession.getContextKey().equals(queue.getOwner()))
+ else if(queue.getOwner() != null && !session.getContextKey().equals(queue.getOwner()))
{
// todo - constant
throw body.getChannelException(405, "Cannot declare queue, as exclusive queue with same name declared on another connection");
@@ -118,25 +120,26 @@ public class QueueDeclareHandler implements StateAwareMethodListener<QueueDeclar
_log.info("Queue " + body.queue + " exists and is accesible to this connection [owner=" + queue.getOwner() +"]");
}
//set this as the default queue on the channel:
- protocolSession.getChannel(evt.getChannelId()).setDefaultQueue(queue);
+ session.getChannel(evt.getChannelId()).setDefaultQueue(queue);
}
+
if (!body.nowait)
{
// Be aware of possible changes to parameter order as versions change.
AMQMethodBody response = QueueDeclareOkBody.createMethodBody(
- protocolSession.getMajor(), // AMQP major version
- protocolSession.getMinor(), // AMQP minor version
+ session.getProtocolMajorVersion(), // AMQP major version
+ session.getProtocolMinorVersion(), // AMQP minor version
queue.getConsumerCount(), // consumerCount
queue.getMessageCount(), // messageCount
body.queue); // queue
_log.info("Queue " + body.queue + " declared successfully");
- protocolSession.writeResponse(evt, response);
+ session.writeResponse(evt, response);
}
}
- protected String createName()
+ protected AMQShortString createName()
{
- return "tmp_" + pad(_counter.incrementAndGet());
+ return new AMQShortString("tmp_" + pad(_counter.incrementAndGet()));
}
protected static String pad(int value)
@@ -144,13 +147,13 @@ public class QueueDeclareHandler implements StateAwareMethodListener<QueueDeclar
return MessageFormat.format("{0,number,0000000000000}", value);
}
- protected AMQQueue createQueue(QueueDeclareBody body, final QueueRegistry registry, final AMQProtocolSession session)
+ protected AMQQueue createQueue(QueueDeclareBody body, VirtualHost virtualHost, final AMQProtocolSession session)
throws AMQException
{
- String owner = body.exclusive ? session.getContextKey() : null;
- if (owner != null) _log.info("Queue " + body.queue + " is owned by " + owner);
- final AMQQueue queue = new AMQQueue(body.queue, body.durable, owner, body.autoDelete, registry);
- final String queueName = queue.getName();
+ final QueueRegistry registry = virtualHost.getQueueRegistry();
+ AMQShortString owner = body.exclusive ? session.getContextKey() : null;
+ final AMQQueue queue = new AMQQueue(body.queue, body.durable, owner, body.autoDelete, virtualHost);
+ final AMQShortString queueName = queue.getName();
if(body.exclusive && !body.durable)
{
@@ -178,7 +181,6 @@ public class QueueDeclareHandler implements StateAwareMethodListener<QueueDeclar
}
});
-
}
return queue;
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/QueueDeleteHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/QueueDeleteHandler.java
index 8ada41572c..69232d5cce 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/QueueDeleteHandler.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/handler/QueueDeleteHandler.java
@@ -20,21 +20,25 @@
*/
package org.apache.qpid.server.handler;
+import org.apache.qpid.AMQException;
+import org.apache.qpid.framing.QueueDeleteBody;
+import org.apache.qpid.framing.QueueDeleteOkBody;
import org.apache.qpid.protocol.AMQMethodEvent;
-import org.apache.qpid.server.state.StateAwareMethodListener;
-import org.apache.qpid.server.state.AMQStateManager;
-import org.apache.qpid.server.queue.QueueRegistry;
-import org.apache.qpid.server.queue.AMQQueue;
-import org.apache.qpid.server.exchange.ExchangeRegistry;
import org.apache.qpid.server.protocol.AMQProtocolSession;
+import org.apache.qpid.server.queue.AMQQueue;
+import org.apache.qpid.server.queue.QueueRegistry;
+import org.apache.qpid.server.state.AMQStateManager;
+import org.apache.qpid.server.state.StateAwareMethodListener;
import org.apache.qpid.server.store.MessageStore;
import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.framing.QueueDeleteBody;
-import org.apache.qpid.framing.QueueDeleteOkBody;
-import org.apache.qpid.AMQException;
+import org.apache.qpid.server.virtualhost.VirtualHost;
+
+//import org.apache.log4j.Logger;
public class QueueDeleteHandler implements StateAwareMethodListener<QueueDeleteBody>
{
+ //private static final Logger _log = Logger.getLogger(QueueDeleteHandler.class);
+
private static final QueueDeleteHandler _instance = new QueueDeleteHandler();
public static QueueDeleteHandler getInstance()
@@ -43,7 +47,6 @@ public class QueueDeleteHandler implements StateAwareMethodListener<QueueDelete
}
private final boolean _failIfNotFound;
- private final MessageStore _store;
public QueueDeleteHandler()
{
@@ -53,12 +56,15 @@ public class QueueDeleteHandler implements StateAwareMethodListener<QueueDelete
public QueueDeleteHandler(boolean failIfNotFound)
{
_failIfNotFound = failIfNotFound;
- _store = ApplicationRegistry.getInstance().getMessageStore();
-
}
- public void methodReceived(AMQProtocolSession session, AMQMethodEvent<QueueDeleteBody> evt) throws AMQException
+ public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<QueueDeleteBody> evt) throws AMQException
{
+ AMQProtocolSession session = stateManager.getProtocolSession();
+ VirtualHost virtualHost = session.getVirtualHost();
+ QueueRegistry queueRegistry = virtualHost.getQueueRegistry();
+ MessageStore store = virtualHost.getMessageStore();
+
QueueDeleteBody body = evt.getMethod();
AMQQueue queue;
if(body.queue == null)
@@ -67,7 +73,7 @@ public class QueueDeleteHandler implements StateAwareMethodListener<QueueDelete
}
else
{
- queue = session.getQueueRegistry().getQueue(body.queue);
+ queue = queueRegistry.getQueue(body.queue);
}
if(queue == null)
@@ -92,12 +98,12 @@ public class QueueDeleteHandler implements StateAwareMethodListener<QueueDelete
else
{
int purged = queue.delete(body.ifUnused, body.ifEmpty);
- _store.removeQueue(queue.getName());
+ store.removeQueue(queue.getName());
// Be aware of possible changes to parameter order as versions change.
session.writeResponse(evt, QueueDeleteOkBody.createMethodBody(
- session.getMajor(), // AMQP major version
- session.getMinor(), // AMQP minor version
- purged)); // messageCount
+ session.getProtocolMajorVersion(), // AMQP major version
+ session.getProtocolMinorVersion(), // AMQP minor version
+ purged)); // messageCount
}
}
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/QueuePurgeHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/QueuePurgeHandler.java
index 0cec10cc1e..1933acee13 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/QueuePurgeHandler.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/handler/QueuePurgeHandler.java
@@ -1,20 +1,47 @@
+/*
+ *
+ * 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.handler;
-import org.apache.qpid.framing.*;
+import org.apache.qpid.AMQException;
+import org.apache.qpid.framing.AMQMethodBody;
+import org.apache.qpid.framing.QueuePurgeBody;
+import org.apache.qpid.framing.QueuePurgeOkBody;
+import org.apache.qpid.protocol.AMQConstant;
+import org.apache.qpid.protocol.AMQMethodEvent;
+import org.apache.qpid.server.AMQChannel;
+import org.apache.qpid.server.protocol.AMQProtocolSession;
+import org.apache.qpid.server.queue.AMQQueue;
+import org.apache.qpid.server.queue.QueueRegistry;
+import org.apache.qpid.server.registry.ApplicationRegistry;
import org.apache.qpid.server.state.StateAwareMethodListener;
import org.apache.qpid.server.state.AMQStateManager;
import org.apache.qpid.server.store.MessageStore;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.server.queue.QueueRegistry;
-import org.apache.qpid.server.queue.AMQQueue;
-import org.apache.qpid.server.exchange.ExchangeRegistry;
-import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.protocol.AMQMethodEvent;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.protocol.AMQConstant;
+import org.apache.qpid.server.virtualhost.VirtualHost;
+
+//import org.apache.log4j.Logger;
public class QueuePurgeHandler implements StateAwareMethodListener<QueuePurgeBody>
{
+ //private static final Logger _log = Logger.getLogger(QueuePurgeHandler.class);
+
private static final QueuePurgeHandler _instance = new QueuePurgeHandler();
public static QueuePurgeHandler getInstance()
@@ -34,9 +61,11 @@ public class QueuePurgeHandler implements StateAwareMethodListener<QueuePurgeBod
_failIfNotFound = failIfNotFound;
}
- public void methodReceived(AMQProtocolSession session, AMQMethodEvent<QueuePurgeBody> evt) throws AMQException
+ public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<QueuePurgeBody> evt) throws AMQException
{
- QueueRegistry queueRegistry = session.getQueueRegistry();
+ AMQProtocolSession session = stateManager.getProtocolSession();
+ VirtualHost virtualHost = session.getVirtualHost();
+ QueueRegistry queueRegistry = virtualHost.getQueueRegistry();
QueuePurgeBody body = evt.getMethod();
AMQQueue queue;
@@ -66,15 +95,16 @@ public class QueuePurgeHandler implements StateAwareMethodListener<QueuePurgeBod
}
else
{
- long purged = queue.clearQueue();
-
+ AMQChannel channel = session.getChannel(evt.getChannelId());
+ long purged = queue.clearQueue(channel.getStoreContext());
if(!body.nowait)
{
- AMQMethodBody response
- = QueuePurgeOkBody.createMethodBody(session.getMajor(), session.getMinor(), purged);
+ AMQMethodBody response = QueuePurgeOkBody.createMethodBody(
+ session.getProtocolMajorVersion(), // AMQP major version
+ session.getProtocolMinorVersion(), // AMQP minor version
+ purged);
session.writeResponse(evt, response);
-
}
}
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/TxCommitHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/TxCommitHandler.java
index 73d9a76bd9..395ec2bf4d 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/TxCommitHandler.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/handler/TxCommitHandler.java
@@ -7,9 +7,9 @@
* 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
@@ -25,14 +25,16 @@ import org.apache.qpid.framing.TxCommitBody;
import org.apache.qpid.framing.TxCommitOkBody;
import org.apache.qpid.protocol.AMQMethodEvent;
import org.apache.qpid.server.AMQChannel;
-import org.apache.qpid.server.exchange.ExchangeRegistry;
import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.state.AMQStateManager;
import org.apache.qpid.server.state.StateAwareMethodListener;
+import org.apache.log4j.Logger;
+
public class TxCommitHandler implements StateAwareMethodListener<TxCommitBody>
{
+ private static final Logger _log = Logger.getLogger(TxCommitHandler.class);
+
private static TxCommitHandler _instance = new TxCommitHandler();
public static TxCommitHandler getInstance()
@@ -44,19 +46,26 @@ public class TxCommitHandler implements StateAwareMethodListener<TxCommitBody>
{
}
- public void methodReceived(AMQProtocolSession protocolSession,
- AMQMethodEvent<TxCommitBody> evt) throws AMQException
+ public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<TxCommitBody> evt) throws AMQException
{
+ AMQProtocolSession session = stateManager.getProtocolSession();
- try{
- AMQChannel channel = protocolSession.getChannel(evt.getChannelId());
+ try
+ {
+ if (_log.isDebugEnabled())
+ {
+ _log.debug("Commit received on channel " + evt.getChannelId());
+ }
+ AMQChannel channel = session.getChannel(evt.getChannelId());
channel.commit();
// Be aware of possible changes to parameter order as versions change.
- protocolSession.writeResponse(evt, TxCommitOkBody.createMethodBody(
- protocolSession.getMajor(), // AMQP major version
- protocolSession.getMinor())); // AMQP minor version
- channel.processReturns(protocolSession);
- }catch(AMQException e){
+ session.writeResponse(evt, TxCommitOkBody.createMethodBody(
+ session.getProtocolMajorVersion(), // AMQP major version
+ session.getProtocolMinorVersion())); // AMQP minor version
+ channel.processReturns(session);
+ }
+ catch(AMQException e)
+ {
throw evt.getMethod().getChannelException(e.getErrorCode(), "Failed to commit: " + e.getMessage());
}
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/TxRollbackHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/TxRollbackHandler.java
index a2f0af9ad4..f220809927 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/TxRollbackHandler.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/handler/TxRollbackHandler.java
@@ -24,15 +24,17 @@ import org.apache.qpid.AMQException;
import org.apache.qpid.framing.TxRollbackBody;
import org.apache.qpid.framing.TxRollbackOkBody;
import org.apache.qpid.protocol.AMQMethodEvent;
-import org.apache.qpid.server.exchange.ExchangeRegistry;
+import org.apache.qpid.server.AMQChannel;
import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.state.AMQStateManager;
import org.apache.qpid.server.state.StateAwareMethodListener;
-import org.apache.qpid.server.AMQChannel;
+
+//import org.apache.log4j.Logger;
public class TxRollbackHandler implements StateAwareMethodListener<TxRollbackBody>
{
+ //private static final Logger _log = Logger.getLogger(TxRollbackHandler.class);
+
private static TxRollbackHandler _instance = new TxRollbackHandler();
public static TxRollbackHandler getInstance()
@@ -44,20 +46,24 @@ public class TxRollbackHandler implements StateAwareMethodListener<TxRollbackBod
{
}
- public void methodReceived(AMQProtocolSession protocolSession,
- AMQMethodEvent<TxRollbackBody> evt) throws AMQException
+ public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<TxRollbackBody> evt) throws AMQException
{
- try{
- AMQChannel channel = protocolSession.getChannel(evt.getChannelId());
+ AMQProtocolSession session = stateManager.getProtocolSession();
+
+ try
+ {
+ AMQChannel channel = session.getChannel(evt.getChannelId());
channel.rollback();
// Be aware of possible changes to parameter order as versions change.
- protocolSession.writeResponse(evt, TxRollbackOkBody.createMethodBody(
- protocolSession.getMajor(), // AMQP major version
- protocolSession.getMinor())); // AMQP minor version
+ session.writeResponse(evt, TxRollbackOkBody.createMethodBody(
+ session.getProtocolMajorVersion(), // AMQP major version
+ session.getProtocolMinorVersion())); // AMQP minor version
//Now resend all the unacknowledged messages back to the original subscribers.
//(Must be done after the TxnRollback-ok response).
- channel.resend(protocolSession);
- }catch(AMQException e){
+ channel.resend(session, false);
+ }
+ catch(AMQException e)
+ {
throw evt.getMethod().getChannelException(e.getErrorCode(), "Failed to rollback: " + e.getMessage());
}
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/TxSelectHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/TxSelectHandler.java
index fda7345559..de062c1768 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/handler/TxSelectHandler.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/handler/TxSelectHandler.java
@@ -24,14 +24,16 @@ import org.apache.qpid.AMQException;
import org.apache.qpid.framing.TxSelectBody;
import org.apache.qpid.framing.TxSelectOkBody;
import org.apache.qpid.protocol.AMQMethodEvent;
-import org.apache.qpid.server.exchange.ExchangeRegistry;
import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.state.AMQStateManager;
import org.apache.qpid.server.state.StateAwareMethodListener;
+//import org.apache.log4j.Logger;
+
public class TxSelectHandler implements StateAwareMethodListener<TxSelectBody>
{
+ //private static final Logger _log = Logger.getLogger(TxSelectHandler.class);
+
private static TxSelectHandler _instance = new TxSelectHandler();
public static TxSelectHandler getInstance()
@@ -43,13 +45,14 @@ public class TxSelectHandler implements StateAwareMethodListener<TxSelectBody>
{
}
- public void methodReceived(AMQProtocolSession protocolSession,
- AMQMethodEvent<TxSelectBody> evt) throws AMQException
+ public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<TxSelectBody> evt) throws AMQException
{
- protocolSession.getChannel(evt.getChannelId()).setTransactional(true);
+ AMQProtocolSession session = stateManager.getProtocolSession();
+
+ session.getChannel(evt.getChannelId()).setLocalTransactional();
// Be aware of possible changes to parameter order as versions change.
- protocolSession.writeResponse(evt, TxSelectOkBody.createMethodBody(
- protocolSession.getMajor(), // AMQP major version
- protocolSession.getMinor())); // AMQP minor version
+ session.writeResponse(evt, TxSelectOkBody.createMethodBody(
+ session.getProtocolMajorVersion(), // AMQP major version
+ session.getProtocolMinorVersion())); // AMQP minor version
}
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/management/DefaultManagedObject.java b/java/broker/src/main/java/org/apache/qpid/server/management/DefaultManagedObject.java
index 311eb8add9..4fb091df75 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/management/DefaultManagedObject.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/management/DefaultManagedObject.java
@@ -67,7 +67,7 @@ public abstract class DefaultManagedObject extends StandardMBean implements Mana
{
try
{
- ApplicationRegistry.getInstance().getManagedObjectRegistry().registerObject(this);
+ getManagedObjectRegistry().registerObject(this);
}
catch (JMException e)
{
@@ -75,11 +75,16 @@ public abstract class DefaultManagedObject extends StandardMBean implements Mana
}
}
+ protected ManagedObjectRegistry getManagedObjectRegistry()
+ {
+ return ApplicationRegistry.getInstance().getManagedObjectRegistry();
+ }
+
public void unregister() throws AMQException
{
try
{
- ApplicationRegistry.getInstance().getManagedObjectRegistry().unregisterObject(this);
+ getManagedObjectRegistry().unregisterObject(this);
}
catch (JMException e)
{
@@ -91,14 +96,14 @@ public abstract class DefaultManagedObject extends StandardMBean implements Mana
{
return getObjectInstanceName() + "[" + getType() + "]";
}
+
/**
* Created the ObjectName as per the JMX Specs
* @return ObjectName
* @throws MalformedObjectNameException
*/
- public ObjectName getObjectName()
- throws MalformedObjectNameException
+ public ObjectName getObjectName() throws MalformedObjectNameException
{
String name = getObjectInstanceName();
StringBuffer objectName = new StringBuffer(ManagedObject.DOMAIN);
@@ -113,26 +118,41 @@ public abstract class DefaultManagedObject extends StandardMBean implements Mana
return new ObjectName(objectName.toString());
}
- private String getHierarchicalType(ManagedObject obj)
+ protected ObjectName getObjectNameForSingleInstanceMBean() throws MalformedObjectNameException
+ {
+ StringBuffer objectName = new StringBuffer(ManagedObject.DOMAIN);
+
+ objectName.append(":type=");
+ objectName.append(getHierarchicalType(this));
+
+ String hierarchyName = getHierarchicalName(this);
+ if (hierarchyName != null)
+ {
+ objectName.append(",");
+ objectName.append(hierarchyName.substring(0, hierarchyName.lastIndexOf(",")));
+ }
+
+ return new ObjectName(objectName.toString());
+ }
+
+ protected String getHierarchicalType(ManagedObject obj)
{
- String parentType = null;
if (obj.getParentObject() != null)
{
- parentType = getHierarchicalType(obj.getParentObject()).toString();
+ String parentType = getHierarchicalType(obj.getParentObject()).toString();
return parentType + "." + obj.getType();
}
else
return obj.getType();
}
- private String getHierarchicalName(ManagedObject obj)
+ protected String getHierarchicalName(ManagedObject obj)
{
- String parentName = null;
if (obj.getParentObject() != null)
{
- parentName = obj.getParentObject().getType() + "=" +
- obj.getParentObject().getObjectInstanceName() + ","+
- getHierarchicalName(obj.getParentObject());
+ String parentName = obj.getParentObject().getType() + "=" +
+ obj.getParentObject().getObjectInstanceName() + ","+
+ getHierarchicalName(obj.getParentObject());
return parentName;
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/management/ManagedBroker.java b/java/broker/src/main/java/org/apache/qpid/server/management/ManagedBroker.java
index aec7d6cb73..87d9a577e5 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/management/ManagedBroker.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/management/ManagedBroker.java
@@ -37,7 +37,7 @@ import java.io.IOException;
*/
public interface ManagedBroker
{
- static final String TYPE = "BrokerManager";
+ static final String TYPE = "VirtualHostManager";
/**
* Creates a new Exchange.
diff --git a/java/broker/src/main/java/org/apache/qpid/server/message/jms/JMSMessage.java b/java/broker/src/main/java/org/apache/qpid/server/message/jms/JMSMessage.java
deleted file mode 100644
index 7160a292d6..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/message/jms/JMSMessage.java
+++ /dev/null
@@ -1,301 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- *
- */
-package org.apache.qpid.server.message.jms;
-
-import org.apache.qpid.server.message.MessageDecorator;
-import org.apache.qpid.server.queue.AMQMessage;
-
-import javax.jms.Message;
-import javax.jms.JMSException;
-import javax.jms.Destination;
-import javax.jms.MessageNotWriteableException;
-import java.util.Enumeration;
-
-public class JMSMessage implements MessageDecorator
-{
-
- private AMQMessage _message;
-
- public JMSMessage(AMQMessage message)
- {
- _message = message;
- }
-
- protected void checkWriteable() throws MessageNotWriteableException
- {
- //The broker should not modify a message.
-// if (_readableMessage)
- {
- throw new MessageNotWriteableException("The broker should not modify a message.");
- }
- }
-
-
- public String getJMSMessageID()
- {
- return _message.getXXXMessageId();
- }
-
- public void setJMSMessageID(String string) throws MessageNotWriteableException
- {
- checkWriteable();
- _message.setXXXMessageId(string);
- }
-
- public long getJMSTimestamp()
- {
- return _message.getTimestamp();
- }
-
- public void setJMSTimestamp(long l) throws MessageNotWriteableException
- {
- checkWriteable();
- _message.setTimestamp(l);
- }
-
- public byte[] getJMSCorrelationIDAsBytes()
- {
- return _message.getCorrelationId().getBytes();
- }
-
-// public void setJMSCorrelationIDAsBytes(byte[] bytes)
-// {
-// }
-
- public void setJMSCorrelationID(String string) throws MessageNotWriteableException
- {
- checkWriteable();
- _message.setCorrelationId(string);
- }
-
- public String getJMSCorrelationID()
- {
- return _message.getCorrelationId();
- }
-
- public String getJMSReplyTo()
- {
- return _message.getReplyTo();
- }
-
- public void setJMSReplyTo(Destination destination) throws MessageNotWriteableException
- {
- checkWriteable();
- _message.setReplyTo(destination.toString());
- }
-
- public String getJMSDestination()
- {
- //fixme should be a deestination
- return "";
- }
-
- public void setJMSDestination(Destination destination) throws MessageNotWriteableException
- {
- checkWriteable();
- //_properties.setDestination(destination.toString());
- }
-
- public int getJMSDeliveryMode()
- {
- return _message.getDeliveryMode();
- }
-
- public void setJMSDeliveryMode(byte i) throws MessageNotWriteableException
- {
- checkWriteable();
- _message.setDeliveryMode(i);
- }
-
- public boolean getJMSRedelivered()
- {
- return _message.isRedelivered();
- }
-
- public void setJMSRedelivered(boolean b) throws MessageNotWriteableException
- {
- checkWriteable();
- _message.setRedelivered(b);
- }
-
- public String getJMSType()
- {
- return _message.getType();
- }
-
- public void setJMSType(String string) throws MessageNotWriteableException
- {
- checkWriteable();
- _message.setType(string);
- }
-
- public long getJMSExpiration()
- {
- return _message.getExpiration();
- }
-
- public void setJMSExpiration(long l) throws MessageNotWriteableException
- {
- checkWriteable();
- _message.setExpiration(l);
- }
-
- public int getJMSPriority()
- {
- return _message.getPriority();
- }
-
- public void setJMSPriority(byte i) throws MessageNotWriteableException
- {
- checkWriteable();
- _message.setPriority(i);
- }
-
- public void clearProperties() throws MessageNotWriteableException
- {
- checkWriteable();
- _message.getApplicationHeaders().clear();
- }
-
- public boolean propertyExists(String string)
- {
- return _message.getApplicationHeaders().propertyExists(string);
- }
-
- public boolean getBooleanProperty(String string) throws JMSException
- {
- return _message.getApplicationHeaders().getBoolean(string);
- }
-
- public byte getByteProperty(String string) throws JMSException
- {
- return _message.getApplicationHeaders().getByte(string);
- }
-
- public short getShortProperty(String string) throws JMSException
- {
- return _message.getApplicationHeaders().getShort(string);
- }
-
- public int getIntProperty(String string) throws JMSException
- {
- return _message.getApplicationHeaders().getInteger(string);
- }
-
- public long getLongProperty(String string) throws JMSException
- {
- return _message.getApplicationHeaders().getLong(string);
- }
-
- public float getFloatProperty(String string) throws JMSException
- {
- return _message.getApplicationHeaders().getFloat(string);
- }
-
- public double getDoubleProperty(String string) throws JMSException
- {
- return _message.getApplicationHeaders().getDouble(string);
- }
-
- public String getStringProperty(String string) throws JMSException
- {
- return _message.getApplicationHeaders().getString(string);
- }
-
- public Object getObjectProperty(String string) throws JMSException
- {
- return _message.getApplicationHeaders().getObject(string);
- }
-
- public Enumeration getPropertyNames()
- {
- return _message.getApplicationHeaders().getPropertyNames();
- }
-
- public void setBooleanProperty(String string, boolean b) throws JMSException
- {
- checkWriteable();
- _message.getApplicationHeaders().setBoolean(string, b);
- }
-
- public void setByteProperty(String string, byte b) throws JMSException
- {
- checkWriteable();
- _message.getApplicationHeaders().setByte(string, b);
- }
-
- public void setShortProperty(String string, short i) throws JMSException
- {
- checkWriteable();
- _message.getApplicationHeaders().setShort(string, i);
- }
-
- public void setIntProperty(String string, int i) throws JMSException
- {
- checkWriteable();
- _message.getApplicationHeaders().setInteger(string, i);
- }
-
- public void setLongProperty(String string, long l) throws JMSException
- {
- checkWriteable();
- _message.getApplicationHeaders().setLong(string, l);
- }
-
- public void setFloatProperty(String string, float v) throws JMSException
- {
- checkWriteable();
- _message.getApplicationHeaders().setFloat(string, v);
- }
-
- public void setDoubleProperty(String string, double v) throws JMSException
- {
- checkWriteable();
- _message.getApplicationHeaders().setDouble(string, v);
- }
-
- public void setStringProperty(String string, String string1) throws JMSException
- {
- checkWriteable();
- _message.getApplicationHeaders().setString(string, string1);
- }
-
- public void setObjectProperty(String string, Object object) throws JMSException
- {
- checkWriteable();
- _message.getApplicationHeaders().setObject(string, object);
- }
-
- public void acknowledge() throws MessageNotWriteableException
- {
- checkWriteable();
- }
-
- public void clearBody() throws MessageNotWriteableException
- {
- checkWriteable();
- }
-
- public AMQMessage getAMQMessage()
- {
- return _message;
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQMinaProtocolSession.java b/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQMinaProtocolSession.java
index c30e8eaab4..bf8d541a44 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQMinaProtocolSession.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQMinaProtocolSession.java
@@ -23,11 +23,14 @@ package org.apache.qpid.server.protocol;
import org.apache.log4j.Logger;
import org.apache.mina.common.IdleStatus;
import org.apache.mina.common.IoSession;
+import org.apache.mina.common.IoSessionConfig;
+import org.apache.mina.common.IoServiceConfig;
import org.apache.mina.transport.vmpipe.VmPipeAddress;
import org.apache.qpid.AMQChannelException;
import org.apache.qpid.AMQConnectionException;
import org.apache.qpid.AMQException;
import org.apache.qpid.framing.AMQDataBlock;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.framing.AMQProtocolVersionException;
import org.apache.qpid.framing.ProtocolInitiation;
import org.apache.qpid.framing.ConnectionStartBody;
@@ -49,14 +52,16 @@ import org.apache.qpid.framing.RequestManager;
import org.apache.qpid.framing.ResponseManager;
import org.apache.qpid.framing.RequestResponseMappingException;
import org.apache.qpid.framing.MessageTransferBody;
+import org.apache.qpid.framing.MainRegistry;
+import org.apache.qpid.framing.VersionSpecificRegistry;
import org.apache.qpid.common.ClientProperties;
import org.apache.qpid.codec.AMQCodecFactory;
import org.apache.qpid.codec.AMQDecoder;
import org.apache.qpid.protocol.AMQMethodEvent;
import org.apache.qpid.protocol.AMQMethodListener;
+import org.apache.qpid.pool.ReadWriteThreadModel;
import org.apache.qpid.server.AMQChannel;
-import org.apache.qpid.server.RequiredDeliveryException;
import org.apache.qpid.server.exchange.ExchangeRegistry;
import org.apache.qpid.server.management.Managable;
import org.apache.qpid.server.management.ManagedObject;
@@ -65,6 +70,9 @@ import org.apache.qpid.server.registry.ApplicationRegistry;
import org.apache.qpid.server.registry.IApplicationRegistry;
import org.apache.qpid.server.state.AMQStateManager;
import org.apache.qpid.server.state.AMQState;
+import org.apache.qpid.server.store.MessageStore;
+import org.apache.qpid.server.virtualhost.VirtualHost;
+import org.apache.qpid.server.virtualhost.VirtualHostRegistry;
import javax.management.JMException;
import javax.security.sasl.SaslServer;
@@ -76,7 +84,7 @@ import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.CopyOnWriteArrayList;
-import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
public class AMQMinaProtocolSession implements AMQProtocolSession,
ProtocolVersionList,
@@ -86,19 +94,26 @@ public class AMQMinaProtocolSession implements AMQProtocolSession,
private static final String CLIENT_PROPERTIES_INSTANCE = ClientProperties.instance.toString();
+ // to save boxing the channelId and looking up in a map... cache in an array the low numbered
+ // channels. This value must be of the form 2^x - 1.
+ private static final int CHANNEL_CACHE_SIZE = 0xff;
+
private final IoSession _minaProtocolSession;
- private String _contextKey;
+ private AMQShortString _contextKey;
+
+ private VirtualHost _virtualHost;
private final Map<Integer, AMQChannel> _channelMap = new HashMap<Integer, AMQChannel>();
+ private final AMQChannel[] _cachedChannels = new AMQChannel[CHANNEL_CACHE_SIZE+1];
+
private final CopyOnWriteArraySet<AMQMethodListener> _frameListeners = new CopyOnWriteArraySet<AMQMethodListener>();
private final AMQStateManager _stateManager;
- private final QueueRegistry _queueRegistry;
-
- private final ExchangeRegistry _exchangeRegistry;
+ private ExchangeRegistry _exchangeRegistry;
+ private MessageStore _messageStore;
private AMQCodecFactory _codecFactory;
@@ -118,15 +133,15 @@ public class AMQMinaProtocolSession implements AMQProtocolSession,
private long _maxFrameSize = 65536;
/* AMQP Version for this session */
- private byte _major;
- private byte _minor;
+ private byte _major = pv[pv.length-1][PROTOCOL_MAJOR];
+ private byte _minor = pv[pv.length-1][PROTOCOL_MINOR];
private FieldTable _clientProperties;
-
private final List<Task> _taskList = new CopyOnWriteArrayList<Task>();
+ private VersionSpecificRegistry _registry = MainRegistry.getVersionSpecificRegistry(pv[pv.length-1][PROTOCOL_MAJOR],pv[pv.length-1][PROTOCOL_MINOR]);
// Keeps a tally of connections for logging and debugging
- private static AtomicInteger _ConnectionId;
- static { _ConnectionId = new AtomicInteger(0); }
+ private static AtomicLong _ConnectionId;
+ static { _ConnectionId = new AtomicLong(0L); }
public ManagedObject getManagedObject()
{
@@ -134,26 +149,41 @@ public class AMQMinaProtocolSession implements AMQProtocolSession,
}
- public AMQMinaProtocolSession(IoSession session, QueueRegistry queueRegistry, ExchangeRegistry exchangeRegistry,
+ public AMQMinaProtocolSession(IoSession session, VirtualHostRegistry virtualHostRegistry,
AMQCodecFactory codecFactory)
throws AMQException
{
_ConnectionId.incrementAndGet();
- _stateManager = new AMQStateManager(queueRegistry, exchangeRegistry, this);
+ _stateManager = new AMQStateManager(virtualHostRegistry, this);
_minaProtocolSession = session;
session.setAttachment(this);
- _frameListeners.add(_stateManager);
- _queueRegistry = queueRegistry;
- _exchangeRegistry = exchangeRegistry;
_codecFactory = codecFactory;
- _managedObject = createMBean();
- _managedObject.register();
+ _exchangeRegistry = null;
+ _messageStore = null;
+
_closePending = false;
_closed = false;
- createChannel(0);
- }
+ createChannel(0); // Required to handle requests / responses for channel 0
+
+ _frameListeners.add(_stateManager);
+ _managedObject = createMBean();
+ _managedObject.register();
- public AMQMinaProtocolSession(IoSession session, QueueRegistry queueRegistry, ExchangeRegistry exchangeRegistry,
+ try
+ {
+ IoServiceConfig config = session.getServiceConfig();
+ ReadWriteThreadModel threadModel = (ReadWriteThreadModel) config.getThreadModel();
+ threadModel.getAsynchronousReadFilter().createNewJobForSession(session);
+ threadModel.getAsynchronousWriteFilter().createNewJobForSession(session);
+ }
+ catch (RuntimeException e)
+ {
+ e.printStackTrace();
+ // throw e;
+ }
+ }
+
+ public AMQMinaProtocolSession(IoSession session, VirtualHostRegistry virtualHostRegistry,
AMQCodecFactory codecFactory, AMQStateManager stateManager)
throws AMQException
{
@@ -161,15 +191,14 @@ public class AMQMinaProtocolSession implements AMQProtocolSession,
_stateManager = stateManager;
_minaProtocolSession = session;
session.setAttachment(this);
- _frameListeners.add(_stateManager);
- _queueRegistry = queueRegistry;
- _exchangeRegistry = exchangeRegistry;
+
_codecFactory = codecFactory;
- _managedObject = createMBean();
- _managedObject.register();
+ _exchangeRegistry = null;
+ _messageStore = null;
+
_closePending = false;
_closed = false;
- createChannel(0);
+ createChannel(0); // Required to handle requests / responses for channel 0
}
private AMQProtocolSessionMBean createMBean() throws AMQException
@@ -197,8 +226,7 @@ public class AMQMinaProtocolSession implements AMQProtocolSession,
private AMQChannel createChannel(int id) throws AMQException
{
- IApplicationRegistry registry = ApplicationRegistry.getInstance();
- AMQChannel channel = new AMQChannel(id, this, registry.getMessageStore(),
+ AMQChannel channel = new AMQChannel(id, this, _messageStore,
_exchangeRegistry, _stateManager);
addChannel(channel);
return channel;
@@ -217,10 +245,12 @@ public class AMQMinaProtocolSession implements AMQProtocolSession,
try
{
pi.checkVersion(this); // Fails if not correct
+
// This sets the protocol version (and hence framing classes) for this session.
- _major = pi.protocolMajor;
- _minor = pi.protocolMinor;
+ setProtocolVersion(pi.protocolMajor,pi.protocolMinor);
+
String mechanisms = ApplicationRegistry.getInstance().getAuthenticationManager().getMechanisms();
+
String locales = "en_US";
// Interfacing with generated code - be aware of possible changes to parameter order as versions change.
AMQMethodBody connectionStartBody = ConnectionStartBody.createMethodBody
@@ -251,15 +281,15 @@ public class AMQMinaProtocolSession implements AMQProtocolSession,
else if(!_closed)
{
AMQFrame frame = (AMQFrame) message;
- AMQChannel channel = getChannel(frame.channel);
+ AMQChannel channel = getChannel(frame.getChannel());
if (_closePending)
{
// If a close is pending (ie ChannelClose has been sent, but no ChannelCloseOk received), then
// all methods except ChannelCloseOk must be rejected. (AMQP spec)
- if((frame.bodyFrame instanceof AMQRequestBody))
+ if((frame.getBodyFrame() instanceof AMQRequestBody))
throw new AMQException("Incoming request frame on connection which is pending close.");
- AMQRequestBody requestBody = (AMQRequestBody)frame.bodyFrame;
+ AMQRequestBody requestBody = (AMQRequestBody)frame.getBodyFrame();
if (!(requestBody.getMethodPayload() instanceof ConnectionCloseOkBody))
throw new AMQException("Incoming frame on closing connection is not a Connection.CloseOk method.");
}
@@ -271,9 +301,9 @@ public class AMQMinaProtocolSession implements AMQProtocolSession,
// b. Have a request id of 1 (i.e. the first request on a new channel);
// c. Must be a ConnectionOpenBody method.
// Throw an exception for all other incoming frames on an unopened channel
- if(!(frame.bodyFrame instanceof AMQRequestBody))
+ if(!(frame.getBodyFrame() instanceof AMQRequestBody))
throw new AMQException("Incoming frame on unopened channel is not a request.");
- AMQRequestBody requestBody = (AMQRequestBody)frame.bodyFrame;
+ AMQRequestBody requestBody = (AMQRequestBody)frame.getBodyFrame();
if (!(requestBody.getMethodPayload() instanceof ChannelOpenBody)) {
closeSessionRequest(
requestBody.getMethodPayload().getConnectionException(
@@ -283,16 +313,16 @@ public class AMQMinaProtocolSession implements AMQProtocolSession,
}
if (requestBody.getRequestId() != 1)
throw new AMQException("Incoming Channel.Open frame on unopened channel does not have a request id = 1.");
- channel = createChannel(frame.channel);
+ channel = createChannel(frame.getChannel());
}
- if (frame.bodyFrame instanceof AMQRequestBody)
+ if (frame.getBodyFrame() instanceof AMQRequestBody)
{
- requestFrameReceived(frame.channel, (AMQRequestBody)frame.bodyFrame);
+ requestFrameReceived(frame.getChannel(), (AMQRequestBody)frame.getBodyFrame());
}
- else if (frame.bodyFrame instanceof AMQResponseBody)
+ else if (frame.getBodyFrame() instanceof AMQResponseBody)
{
- responseFrameReceived(frame.channel, (AMQResponseBody)frame.bodyFrame);
+ responseFrameReceived(frame.getChannel(), (AMQResponseBody)frame.getBodyFrame());
}
else
{
@@ -303,10 +333,11 @@ public class AMQMinaProtocolSession implements AMQProtocolSession,
private void requestFrameReceived(int channelNum, AMQRequestBody requestBody) throws Exception
{
- try{
+ try
+ {
if (_logger.isDebugEnabled())
{
- _logger.debug("Request frame received: " + requestBody);
+ _logger.debug("Request frame received: " + requestBody);
}
AMQChannel channel = getChannel(channelNum);
ResponseManager responseManager = channel.getResponseManager();
@@ -383,12 +414,12 @@ public class AMQMinaProtocolSession implements AMQProtocolSession,
_minaProtocolSession.write(frame);
}
- public String getContextKey()
+ public AMQShortString getContextKey()
{
return _contextKey;
}
- public void setContextKey(String contextKey)
+ public void setContextKey(AMQShortString contextKey)
{
_contextKey = contextKey;
}
@@ -400,7 +431,9 @@ public class AMQMinaProtocolSession implements AMQProtocolSession,
public AMQChannel getChannel(int channelId)
{
- return _channelMap.get(channelId);
+ return ((channelId & CHANNEL_CACHE_SIZE) == channelId)
+ ? _cachedChannels[channelId]
+ : _channelMap.get(channelId);
}
public void addChannel(AMQChannel channel)
@@ -410,7 +443,13 @@ public class AMQMinaProtocolSession implements AMQProtocolSession,
throw new IllegalStateException("Session is closed");
}
- _channelMap.put(channel.getChannelId(), channel);
+ final int channelId = channel.getChannelId();
+ _channelMap.put(channelId, channel);
+
+ if(((channelId & CHANNEL_CACHE_SIZE) == channelId))
+ {
+ _cachedChannels[channelId] = channel;
+ }
checkForNotification();
}
@@ -450,7 +489,7 @@ public class AMQMinaProtocolSession implements AMQProtocolSession,
}
// Used to initiate a channel close from the server side and inform the client
- public void closeChannelRequest(int channelId, int replyCode, String replyText) throws AMQException
+ public void closeChannelRequest(int channelId, int replyCode, AMQShortString replyText) throws AMQException
{
final AMQChannel channel = _channelMap.get(channelId);
if (channel == null)
@@ -481,7 +520,7 @@ public class AMQMinaProtocolSession implements AMQProtocolSession,
// Used to close a channel as a response to a client close request
public void closeChannelResponse(int channelId, long requestId) throws AMQException
{
- final AMQChannel channel = _channelMap.get(channelId);
+ final AMQChannel channel = getChannel(channelId);
if (channel == null)
{
throw new IllegalArgumentException("Unknown channel id");
@@ -497,13 +536,14 @@ public class AMQMinaProtocolSession implements AMQProtocolSession,
}
finally
{
- _channelMap.remove(channelId);
+ removeChannel(channelId);
+
}
}
}
// Used to initiate a connection close from the server side and inform the client
- public void closeSessionRequest(int replyCode, String replyText, int classId, int methodId) throws AMQException
+ public void closeSessionRequest(int replyCode, AMQShortString replyText, int classId, int methodId) throws AMQException
{
_closePending = true; // This prevents all methods except Close-Ok from being accepted
_stateManager.changeState(AMQState.CONNECTION_CLOSING);
@@ -523,7 +563,7 @@ public class AMQMinaProtocolSession implements AMQProtocolSession,
closeSession();
}
- public void closeSessionRequest(int replyCode, String replyText) throws AMQException
+ public void closeSessionRequest(int replyCode, AMQShortString replyText) throws AMQException
{
closeSessionRequest(replyCode, replyText, 0, 0);
}
@@ -531,7 +571,7 @@ public class AMQMinaProtocolSession implements AMQProtocolSession,
public void closeSessionRequest(AMQConnectionException e) throws AMQException
{
- closeSessionRequest(e.getErrorCode(), e.getMessage(), e.getClassId(), e.getMethodId());
+ closeSessionRequest(e.getErrorCode(), new AMQShortString(e.getMessage()), e.getClassId(), e.getMethodId());
}
@@ -569,6 +609,10 @@ public class AMQMinaProtocolSession implements AMQProtocolSession,
public void removeChannel(int channelId)
{
_channelMap.remove(channelId);
+ if((channelId & CHANNEL_CACHE_SIZE) == channelId)
+ {
+ _cachedChannels[channelId] = null;
+ }
}
/**
@@ -614,6 +658,10 @@ public class AMQMinaProtocolSession implements AMQProtocolSession,
channel.close(this);
}
_channelMap.clear();
+ for(int i = 0; i <= CHANNEL_CACHE_SIZE; i++)
+ {
+ _cachedChannels[i]=null;
+ }
}
public String toString()
@@ -679,52 +727,46 @@ public class AMQMinaProtocolSession implements AMQProtocolSession,
_clientProperties = clientProperties;
if((_clientProperties != null) && (_clientProperties.getString(CLIENT_PROPERTIES_INSTANCE) != null))
{
- setContextKey(_clientProperties.getString(CLIENT_PROPERTIES_INSTANCE));
+ setContextKey(new AMQShortString(_clientProperties.getString(CLIENT_PROPERTIES_INSTANCE)));
}
}
- public QueueRegistry getQueueRegistry()
- {
- return _queueRegistry;
- }
-
- public ExchangeRegistry getExchangeRegistry()
- {
- return _exchangeRegistry;
- }
-
public AMQStateManager getStateManager()
{
return _stateManager;
}
- /**
- * Convenience methods for managing AMQP version.
- * NOTE: Both major and minor will be set to 0 prior to protocol initiation.
- */
+ private void setProtocolVersion(byte major, byte minor)
+ {
+ _major = major;
+ _minor = minor;
+ _registry = MainRegistry.getVersionSpecificRegistry(major,minor);
+ }
- public byte getMajor()
+ public byte getProtocolMajorVersion()
{
return _major;
}
- public byte getMinor()
+ public byte getProtocolMinorVersion()
{
return _minor;
}
- public boolean versionEquals(byte major, byte minor)
+ public boolean isProtocolVersionEqual(byte major, byte minor)
{
return _major == major && _minor == minor;
}
- public void checkMethodBodyVersion(AMQMethodBody methodBody) {
- if (!versionEquals(methodBody.getMajor(), methodBody.getMinor())) {
+ public void checkMethodBodyVersion(AMQMethodBody methodBody)
+ {
+ if (!isProtocolVersionEqual(methodBody.getMajor(), methodBody.getMinor()))
+ {
throw new RuntimeException("MethodBody version did not match version of current session.");
}
}
- public int getConnectionId()
+ public long getConnectionId()
{
return _ConnectionId.get();
}
@@ -743,4 +785,24 @@ public class AMQMinaProtocolSession implements AMQProtocolSession,
{
_taskList.remove(task);
}
+
+ public VersionSpecificRegistry getRegistry()
+ {
+ return _registry;
+ }
+
+
+ public VirtualHost getVirtualHost()
+ {
+ return _virtualHost;
+ }
+
+ public void setVirtualHost(VirtualHost virtualHost) throws AMQException
+ {
+ _virtualHost = virtualHost;
+ _exchangeRegistry = virtualHost.getExchangeRegistry();
+ _messageStore = virtualHost.getMessageStore();
+ _managedObject = createMBean();
+ _managedObject.register();
+ }
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQPFastProtocolHandler.java b/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQPFastProtocolHandler.java
index b3c97669c5..26b7bc6992 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQPFastProtocolHandler.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQPFastProtocolHandler.java
@@ -54,41 +54,26 @@ public class AMQPFastProtocolHandler extends IoHandlerAdapter implements Protoco
{
private static final Logger _logger = Logger.getLogger(AMQPFastProtocolHandler.class);
- /**
- * The registry of all queues. This is passed to frame listeners when frame
- * events occur.
- */
- private final QueueRegistry _queueRegistry;
+ private final IApplicationRegistry _applicationRegistry;
- /**
- * The registry of all exchanges. This is passed to frame listeners when frame
- * events occur.
- */
- private final ExchangeRegistry _exchangeRegistry;
private boolean _useSSL;
public AMQPFastProtocolHandler(Integer applicationRegistryInstance)
{
- IApplicationRegistry registry = ApplicationRegistry.getInstance(applicationRegistryInstance);
-
- _queueRegistry = registry.getQueueRegistry();
- _exchangeRegistry = registry.getExchangeRegistry();
- _logger.debug("AMQPFastProtocolHandler created");
+ this(ApplicationRegistry.getInstance(applicationRegistryInstance));
}
- public AMQPFastProtocolHandler(QueueRegistry queueRegistry,
- ExchangeRegistry exchangeRegistry)
+ public AMQPFastProtocolHandler(IApplicationRegistry applicationRegistry)
{
- _queueRegistry = queueRegistry;
- _exchangeRegistry = exchangeRegistry;
+ _applicationRegistry = applicationRegistry;
_logger.debug("AMQPFastProtocolHandler created");
}
protected AMQPFastProtocolHandler(AMQPFastProtocolHandler handler)
{
- this(handler._queueRegistry, handler._exchangeRegistry);
+ this(handler._applicationRegistry);
}
public void sessionCreated(IoSession protocolSession) throws Exception
@@ -96,7 +81,7 @@ public class AMQPFastProtocolHandler extends IoHandlerAdapter implements Protoco
SessionUtil.initialize(protocolSession);
final AMQCodecFactory codecFactory = new AMQCodecFactory(true);
- createSession(protocolSession, _queueRegistry, _exchangeRegistry, codecFactory);
+ createSession(protocolSession, _applicationRegistry, codecFactory);
_logger.info("Protocol session created");
final ProtocolCodecFilter pcf = new ProtocolCodecFilter(codecFactory);
@@ -121,9 +106,9 @@ public class AMQPFastProtocolHandler extends IoHandlerAdapter implements Protoco
/**
* Separated into its own, protected, method to allow easier reuse
*/
- protected void createSession(IoSession session, QueueRegistry queues, ExchangeRegistry exchanges, AMQCodecFactory codec) throws AMQException
+ protected void createSession(IoSession session, IApplicationRegistry applicationRegistry, AMQCodecFactory codec) throws AMQException
{
- new AMQMinaProtocolSession(session, queues, exchanges, codec);
+ new AMQMinaProtocolSession(session, applicationRegistry.getVirtualHostRegistry(), codec);
}
public void sessionOpened(IoSession protocolSession) throws Exception
@@ -135,7 +120,11 @@ public class AMQPFastProtocolHandler extends IoHandlerAdapter implements Protoco
{
_logger.info("Protocol Session closed");
final AMQProtocolSession amqProtocolSession = AMQMinaProtocolSession.getAMQProtocolSession(protocolSession);
- amqProtocolSession.closeSession();
+ //fixme -- this can be null
+ if(amqProtocolSession != null)
+ {
+ amqProtocolSession.closeSession();
+ }
}
public void sessionIdle(IoSession session, IdleStatus status) throws Exception
@@ -154,8 +143,7 @@ public class AMQPFastProtocolHandler extends IoHandlerAdapter implements Protoco
}
- public void exceptionCaught(IoSession protocolSession, AMQMethodListener methodListener,
- Throwable throwable) throws Exception
+ public void exceptionCaught(IoSession protocolSession, Throwable throwable) throws Exception
{
AMQProtocolSession session = AMQMinaProtocolSession.getAMQProtocolSession(protocolSession);
if (throwable instanceof AMQProtocolHeaderException)
@@ -176,7 +164,7 @@ public class AMQPFastProtocolHandler extends IoHandlerAdapter implements Protoco
{
_logger.error("Exception caught in" + session + ", closing session explictly: " + throwable, throwable);
// TODO: Closing with code 200 ("reply-sucess") ??? This cannot be right!
- session.closeSessionRequest(200, throwable.getMessage());
+ session.closeSessionRequest(200, new AMQShortString(throwable.getMessage()));
}
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQPProtocolProvider.java b/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQPProtocolProvider.java
index ff1316f704..07c153bfe8 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQPProtocolProvider.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQPProtocolProvider.java
@@ -42,8 +42,7 @@ public class AMQPProtocolProvider
public AMQPProtocolProvider()
{
IApplicationRegistry registry = ApplicationRegistry.getInstance();
- _handler = new AMQPFastProtocolHandler(registry.getQueueRegistry(),
- registry.getExchangeRegistry());
+ _handler = new AMQPFastProtocolHandler(registry);
}
public AMQPFastProtocolHandler getHandler()
diff --git a/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolSession.java b/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolSession.java
index 6c99af1c70..723783ab21 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolSession.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolSession.java
@@ -20,21 +20,25 @@
*/
package org.apache.qpid.server.protocol;
+import org.apache.qpid.AMQException;
import org.apache.qpid.framing.AMQDataBlock;
import org.apache.qpid.framing.AMQMethodBody;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.framing.FieldTable;
import org.apache.qpid.protocol.AMQMethodEvent;
+import org.apache.qpid.protocol.AMQProtocolWriter;
+import org.apache.qpid.protocol.AMQVersionAwareProtocolSession;
import org.apache.qpid.server.AMQChannel;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.exchange.ExchangeRegistry;
+import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.state.AMQStateManager;
+import org.apache.qpid.server.virtualhost.VirtualHost;
import javax.security.sasl.SaslServer;
import org.apache.qpid.protocol.AMQProtocolWriter;
-public interface AMQProtocolSession extends AMQProtocolWriter
+public interface AMQProtocolSession extends AMQVersionAwareProtocolSession
{
@@ -56,14 +60,14 @@ public interface AMQProtocolSession extends AMQProtocolWriter
* in the AMQ protocol specification (RFC 6).
* @return the context key
*/
- String getContextKey();
+ AMQShortString getContextKey();
/**
* Set the context key associated with this session. Context key is described
* in the AMQ protocol specification (RFC 6).
* @param contextKey the context key
*/
- void setContextKey(String contextKey);
+ void setContextKey(AMQShortString contextKey);
/**
* Get the channel for this session associated with the specified id. A channel
@@ -80,13 +84,13 @@ public interface AMQProtocolSession extends AMQProtocolWriter
*/
void addChannel(AMQChannel channel) throws AMQException;
- void closeChannelRequest(int channelId, int replyCode, String replyText) throws AMQException;
+ void closeChannelRequest(int channelId, int replyCode, AMQShortString replyText) throws AMQException;
void closeChannelResponse(int channelId, long requestId) throws AMQException;
- void closeSessionRequest(int replyCode, String replyText, int classId, int methodId) throws AMQException;
+ void closeSessionRequest(int replyCode, AMQShortString replyText, int classId, int methodId) throws AMQException;
- void closeSessionRequest(int replyCode, String replyText) throws AMQException;
+ void closeSessionRequest(int replyCode, AMQShortString replyText) throws AMQException;
void closeSessionResponse(long requestId) throws AMQException;
@@ -145,23 +149,23 @@ public interface AMQProtocolSession extends AMQProtocolWriter
*/
void setSaslServer(SaslServer saslServer);
-
FieldTable getClientProperties();
void setClientProperties(FieldTable clientProperties);
- QueueRegistry getQueueRegistry();
- ExchangeRegistry getExchangeRegistry();
AMQStateManager getStateManager();
- byte getMajor();
- byte getMinor();
- boolean versionEquals(byte major, byte minor);
+
void checkMethodBodyVersion(AMQMethodBody methodBody);
- int getConnectionId();
+
+ long getConnectionId();
Object getClientIdentifier();
void addSessionCloseTask(Task task);
void removeSessionCloseTask(Task task);
+
+ VirtualHost getVirtualHost();
+
+ void setVirtualHost(VirtualHost virtualHost) throws AMQException;
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolSessionMBean.java b/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolSessionMBean.java
index 7716ec0d75..8c6929ab81 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolSessionMBean.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolSessionMBean.java
@@ -21,10 +21,12 @@ import org.apache.qpid.AMQException;
import org.apache.qpid.protocol.AMQConstant;
import org.apache.qpid.framing.ConnectionCloseBody;
import org.apache.qpid.framing.AMQMethodBody;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.server.AMQChannel;
import org.apache.qpid.server.management.AMQManagedObject;
import org.apache.qpid.server.management.MBeanConstructor;
import org.apache.qpid.server.management.MBeanDescription;
+import org.apache.qpid.server.management.ManagedObject;
import javax.management.JMException;
import javax.management.MBeanException;
@@ -58,6 +60,8 @@ public class AMQProtocolSessionMBean extends AMQManagedObject implements Managed
private OpenType[] _channelAttributeTypes = {SimpleType.INTEGER, SimpleType.BOOLEAN, SimpleType.STRING, SimpleType.INTEGER};
private CompositeType _channelType = null; // represents the data type for channel data
private TabularType _channelsType = null; // Data type for list of channels type
+ private static final AMQShortString BROKER_MANAGEMENT_CONSOLE_HAS_CLOSING_THE_CONNECTION =
+ new AMQShortString("Broker Management Console has closing the connection.");
@MBeanConstructor("Creates an MBean exposing an AMQ Broker Connection")
public AMQProtocolSessionMBean(AMQMinaProtocolSession session) throws JMException
@@ -90,6 +94,11 @@ public class AMQProtocolSessionMBean extends AMQManagedObject implements Managed
return _session.getIOSession().getRemoteAddress().toString();
}
+ public ManagedObject getParentObject()
+ {
+ return _session.getVirtualHost().getManagedObject();
+ }
+
public Long getWrittenBytes()
{
return _session.getIOSession().getWrittenBytes();
@@ -175,7 +184,7 @@ public class AMQProtocolSessionMBean extends AMQManagedObject implements Managed
for (AMQChannel channel : list)
{
Object[] itemValues = {channel.getChannelId(), channel.isTransactional(),
- (channel.getDefaultQueue() != null) ? channel.getDefaultQueue().getName() : null,
+ (channel.getDefaultQueue() != null) ? channel.getDefaultQueue().getName().asString() : null,
channel.getUnacknowledgedMessageMap().size()};
CompositeData channelData = new CompositeDataSupport(_channelType, _channelAtttibuteNames, itemValues);
@@ -192,11 +201,14 @@ public class AMQProtocolSessionMBean extends AMQManagedObject implements Managed
*/
public void closeConnection() throws JMException
{
- try {
+ try
+ {
_session.closeSessionRequest
(AMQConstant.REPLY_SUCCESS.getCode(), // XXX: Success???
- "Broker Management Console has closing the connection.");
- } catch (AMQException ex) {
+ new AMQShortString("Broker Management Console is closing the connection."));
+ }
+ catch (AMQException ex)
+ {
throw new MBeanException(ex, ex.toString());
}
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/protocol/ExchangeInitialiser.java b/java/broker/src/main/java/org/apache/qpid/server/protocol/ExchangeInitialiser.java
index d1d0bc7e17..8b5f05e8ea 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/protocol/ExchangeInitialiser.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/protocol/ExchangeInitialiser.java
@@ -21,6 +21,7 @@
package org.apache.qpid.server.protocol;
import org.apache.qpid.AMQException;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.exchange.ExchangeDefaults;
import org.apache.qpid.server.exchange.ExchangeFactory;
import org.apache.qpid.server.exchange.ExchangeRegistry;
@@ -37,7 +38,7 @@ public class ExchangeInitialiser
}
private void define(ExchangeRegistry r, ExchangeFactory f,
- String name, String type) throws AMQException
+ AMQShortString name, AMQShortString type) throws AMQException
{
r.registerExchange(f.createExchange(name, type, true, false, 0));
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/AMQMessage.java b/java/broker/src/main/java/org/apache/qpid/server/queue/AMQMessage.java
index 63643923b8..a271b0b6ed 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/AMQMessage.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/queue/AMQMessage.java
@@ -24,10 +24,10 @@ import org.apache.mina.common.ByteBuffer;
import org.apache.qpid.framing.*;
import org.apache.qpid.server.protocol.AMQProtocolSession;
import org.apache.qpid.server.store.MessageStore;
-import org.apache.qpid.server.txn.TxnBuffer;
-import org.apache.qpid.server.message.MessageDecorator;
-import org.apache.qpid.server.message.jms.JMSMessage;
+import org.apache.qpid.server.store.StoreContext;
+//import org.apache.qpid.server.txn.TxnBuffer;
import org.apache.qpid.AMQException;
+import org.apache.qpid.server.txn.TransactionalContext;
import java.util.ArrayList;
import java.util.Iterator;
@@ -38,15 +38,18 @@ import java.util.HashSet;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+import org.apache.log4j.Logger;
/**
* Combines the information that make up a deliverable message into a more manageable form.
*/
public class AMQMessage
{
- public static final String JMS_MESSAGE = "jms.message";
+ private static final Logger _log = Logger.getLogger(AMQMessage.class);
- private final Set<Object> _tokens = new HashSet<Object>();
+ private Set<Object> _tokens;
private AMQProtocolSession _publisher;
@@ -54,17 +57,23 @@ public class AMQMessage
private List<ByteBuffer> _contents;
- private Iterable<ByteBuffer> _dupContentsIterable = new Iterable() {
- public Iterator<ByteBuffer> iterator() {
- return new Iterator() {
+ private Iterable<ByteBuffer> _dupContentsIterable = new Iterable()
+ {
+ public Iterator<ByteBuffer> iterator()
+ {
+ return new Iterator()
+ {
private Iterator<ByteBuffer> iter = _contents.iterator();
- public boolean hasNext() {
+ public boolean hasNext()
+ {
return iter.hasNext();
}
- public ByteBuffer next() {
+ public ByteBuffer next()
+ {
return iter.next().duplicate();
}
- public void remove() {
+ public void remove()
+ {
throw new UnsupportedOperationException();
}
};
@@ -73,10 +82,18 @@ public class AMQMessage
private boolean _redelivered;
- private final long _messageId;
+ private final Long _messageId;
private final AtomicInteger _referenceCount = new AtomicInteger(1);
+ private AMQMessageHandle _messageHandle;
+
+ // TODO: ideally this should be able to go into the transient message date - check this! (RG)
+ private TransactionalContext _txnContext;
+
+// private List<AMQQueue> _destinationQueues = new LinkedList<AMQQueue>();
+ private List<AMQQueue> _destinationQueues = new CopyOnWriteArrayList<AMQQueue>();
+
/**
* Keeps a track of how many bytes we have received in body frames
*/
@@ -95,67 +112,63 @@ public class AMQMessage
private boolean _storeWhenComplete;
/**
- * TxnBuffer for transactionally published messages
- */
- private TxnBuffer _txnBuffer;
-
- /**
* Flag to indicate whether message has been delivered to a
* consumer. Used in implementing return functionality for
* messages published with the 'immediate' flag.
*/
private boolean _deliveredToConsumer;
- private ConcurrentHashMap<String, MessageDecorator> _decodedMessages;
private AtomicBoolean _taken = new AtomicBoolean(false);
- public AMQMessage(MessageStore messageStore, MessageTransferBody transferBody)
+ public AMQMessage(MessageStore messageStore, MessageTransferBody transferBody, TransactionalContext txnContext)
{
- this(messageStore, transferBody, true);
+ this(messageStore, transferBody, txnContext, true);
}
- public AMQMessage(MessageStore messageStore, MessageTransferBody transferBody, boolean storeWhenComplete)
+ public AMQMessage(MessageStore messageStore, MessageTransferBody transferBody, TransactionalContext txnContext, boolean storeWhenComplete)
{
_messageId = messageStore.getNewMessageId();
_transferBody = transferBody;
_store = messageStore;
+ _txnContext = txnContext;
_contents = new LinkedList();
- _decodedMessages = new ConcurrentHashMap<String, MessageDecorator>();
_storeWhenComplete = storeWhenComplete;
}
- public AMQMessage(MessageStore store, long messageId, MessageTransferBody transferBody,
- List<ByteBuffer> contents)
+ public AMQMessage(MessageStore store, long messageId, MessageTransferBody transferBody, List<ByteBuffer> contents, TransactionalContext txnContext)
throws AMQException
{
_transferBody = transferBody;
_contents = contents;
- _decodedMessages = new ConcurrentHashMap<String, MessageDecorator>();
_messageId = messageId;
_store = store;
+ _txnContext = txnContext;
storeMessage();
}
- public AMQMessage(MessageStore store, MessageTransferBody transferBody, List<ByteBuffer> contents)
+ public AMQMessage(MessageStore store, MessageTransferBody transferBody, List<ByteBuffer> contents, TransactionalContext txnContext)
throws AMQException
{
- this(store, store.getNewMessageId(), transferBody, contents);
+ this(store, store.getNewMessageId(), transferBody, contents, txnContext);
}
protected AMQMessage(AMQMessage msg) throws AMQException
{
- this(msg._store, msg._messageId, msg._transferBody, msg._contents);
+ this(msg._store, msg._messageId, msg._transferBody, msg._contents, msg._txnContext);
}
- public long getSize() {
+ public long getSize()
+ {
return getHeaderSize() + getBodySize();
}
- public int getHeaderSize() {
+ public int getHeaderSize()
+ {
int size = _transferBody.getBodySize();
Content body = _transferBody.getBody();
- switch (body.getContentType()) {
+ switch (body.getContentType())
+ {
case INLINE_T:
size -= _transferBody.getBody().getEncodedSize();
break;
@@ -163,102 +176,206 @@ public class AMQMessage
return size;
}
- public long getBodySize() {
- long size = 0;
- for (ByteBuffer buffer : _contents) {
+ public long getBodySize()
+ {
+ long size = 0L;
+ for (ByteBuffer buffer : _contents)
+ {
size += buffer.limit();
}
return size;
}
+
- public FieldTable getApplicationHeaders() {
+ public MessageTransferBody getTransferBody()
+ {
+ return _transferBody;
+ }
+
+ // Get methods (and some set methods) for MessageTransferBody
+
+ public AMQShortString getAppId()
+ {
+ return _transferBody.getAppId();
+ }
+
+ public FieldTable getApplicationHeaders()
+ {
return _transferBody.getApplicationHeaders();
}
-
- public void setXXXMessageId(String messageId) {
- throw new Error("XXX");
+
+ public Content getBody()
+ {
+ return _transferBody.getBody();
}
-
- public String getXXXMessageId() {
- throw new Error("XXX");
+
+ public AMQShortString getContentEncoding()
+ {
+ return _transferBody.getContentEncoding();
}
-
- public void setType(String type) {
- throw new Error("XXX");
+
+ public AMQShortString getContentType()
+ {
+ return _transferBody.getContentType();
}
-
- public String getType() {
- throw new Error("XXX");
+
+ public AMQShortString getCorrelationId()
+ {
+ return _transferBody.getCorrelationId();
}
- public void setDeliveryMode(byte mode) {
- throw new Error("XXX");
+ public void setCorrelationId(AMQShortString correlationId)
+ {
+ // TODO - if/when MethodBody classes have set methods, then the public access
+ // to these members should be revoked
+ _transferBody.correlationId = correlationId;
}
-
- public byte getDeliveryMode() {
- return (byte) _transferBody.deliveryMode;
+
+ public short getDeliveryMode()
+ {
+ return _transferBody.getDeliveryMode();
}
- public void setReplyTo(String replyTo) {
- throw new Error("XXX");
+ public void setDeliveryMode(short deliveryMode)
+ {
+ // TODO - if/when MethodBody classes have set methods, then the public access
+ // to these members should be revoked
+ _transferBody.deliveryMode = deliveryMode;
}
-
- public String getReplyTo() {
- return _transferBody.getReplyTo();
+
+ public AMQShortString getDestination()
+ {
+ return _transferBody.getDestination();
}
-
- public String getAppId() {
- return _transferBody.getAppId();
+
+ public AMQShortString getExchange()
+ {
+ return _transferBody.getExchange();
}
-
- public String getUserId() {
- return _transferBody.getUserId();
+
+ public long getExpiration()
+ {
+ return _transferBody.getExpiration();
}
- public void setCorrelationId(String correlationId) {
- throw new Error("XXX");
+ public void setExpiration(long expiration)
+ {
+ // TODO - if/when MethodBody classes have set methods, then the public access
+ // to these members should be revoked
+ _transferBody.expiration = expiration;
}
-
- public String getCorrelationId() {
- return _transferBody.getCorrelationId();
+
+ public boolean isImmediate()
+ {
+ return _transferBody.getImmediate();
}
-
- public void setPriority(byte priority) {
- throw new Error("XXX");
+
+ public boolean isMandatory()
+ {
+ return _transferBody.getMandatory();
}
+
+ // TODO - how does this relate to _messageId in this class? See other getMessageId() method below.
+// public AMQShortString getMessageId()
+// {
+// return _transferBody.getMessageId();
+// }
- public byte getPriority() {
- return (byte) _transferBody.getPriority();
+ public void setMessageId(AMQShortString messageId)
+ {
+ // TODO - if/when MethodBody classes have set methods, then the public access
+ // to these members should be revoked
+ _transferBody.messageId = messageId;
}
-
- public void setExpiration(long l) {
- throw new Error("XXX");
+
+ public short getPriority()
+ {
+ return _transferBody.getPriority();
}
- public long getExpiration() {
- return _transferBody.getExpiration();
+ public void setPriority(short priority)
+ {
+ // TODO - if/when MethodBody classes have set methods, then the public access
+ // to these members should be revoked
+ _transferBody.priority = priority;
}
- public void setTimestamp(long l) {
- throw new Error("XXX");
+ // TODO - how does this relate to the _redelivered flag in this class? See other isRedelivered() method below.
+// public boolean isRedelivered()
+// {
+// return _transferBody.getRedelivered();
+// }
+
+ public AMQShortString getReplyTo()
+ {
+ return _transferBody.getReplyTo();
}
- public long getTimestamp() {
+ public void setReplyTo(AMQShortString replyTo)
+ {
+ // TODO - if/when MethodBody classes have set methods, then the public access
+ // to these members should be revoked
+ _transferBody.replyTo = replyTo;
+ }
+
+ public AMQShortString getRoutingKey()
+ {
+ return _transferBody.getRoutingKey();
+ }
+
+ public byte[] getSecurityToken()
+ {
+ return _transferBody.getSecurityToken();
+ }
+
+ public int getTicket()
+ {
+ return _transferBody.getTicket();
+ }
+
+ public long getTimestamp()
+ {
return _transferBody.getTimestamp();
}
- public String getContentType() {
- return _transferBody.getContentType();
+ public void setTimestamp(long timestamp)
+ {
+ // TODO - if/when MethodBody classes have set methods, then the public access
+ // to these members should be revoked
+ _transferBody.timestamp = timestamp;
+ }
+
+ public AMQShortString getTransactionId()
+ {
+ return _transferBody.getTransactionId();
+ }
+
+ public long getTtl()
+ {
+ return _transferBody.getTtl();
+ }
+
+ public AMQShortString getUserId()
+ {
+ return _transferBody.getUserId();
}
- public String getEncoding() {
- return _transferBody.getContentEncoding();
+ public void setType(String type)
+ {
+ throw new Error("XXX");
}
- public byte[] getMessageBytes() {
+ public String getType()
+ {
+ throw new Error("XXX");
+ }
+
+ public byte[] getMessageBytes()
+ {
byte[] result = new byte[(int) getBodySize()];
int offset = 0;
- for (ByteBuffer bb : getContents()) {
+ for (ByteBuffer bb : getContents())
+ {
bb.get(result, offset, bb.remaining());
}
return result;
@@ -268,20 +385,17 @@ public class AMQMessage
{
if (isPersistent())
{
- _store.put(this);
+// _store.put(this);
}
}
- public MessageTransferBody getTransferBody()
+ public Iterable<ByteBuffer> getContents()
{
- return _transferBody;
- }
-
- public Iterable<ByteBuffer> getContents() {
return _dupContentsIterable;
}
- public List<AMQBody> getPayload() {
+ public List<AMQBody> getPayload()
+ {
throw new Error("XXX");
}
@@ -298,21 +412,6 @@ public class AMQMessage
return _redelivered;
}
- String getExchangeName()
- {
- return _transferBody.exchange;
- }
-
- String getRoutingKey()
- {
- return _transferBody.routingKey;
- }
-
- boolean isImmediate()
- {
- return _transferBody.immediate;
- }
-
NoConsumersException getNoConsumersException(String queue)
{
return new NoConsumersException(queue, this);
@@ -334,13 +433,17 @@ public class AMQMessage
public void incrementReference()
{
_referenceCount.incrementAndGet();
+ if (_log.isDebugEnabled())
+ {
+ _log.debug("Ref count on message " + _messageId + " incremented to " + _referenceCount);
+ }
}
/**
* Threadsafe. This will decrement the reference count and when it reaches zero will remove the message from the
* message store.
*/
- public void decrementReference() throws MessageCleanupException
+ public void decrementReference(StoreContext storeContext) throws MessageCleanupException
{
// note that the operation of decrementing the reference count and then removing the message does not
// have to be atomic since the ref count starts at 1 and the exchange itself decrements that after
@@ -350,7 +453,20 @@ public class AMQMessage
{
try
{
- _store.removeMessage(_messageId);
+ if (_log.isDebugEnabled())
+ {
+ _log.debug("Ref count on message " + _messageId + " is zero; removing message");
+ }
+
+ // must check if the handle is null since there may be cases where we decide to throw away a message
+ // and the handle has not yet been constructed
+ // New:
+// if (_messageHandle != null)
+// {
+// _messageHandle.removeMessage(storeContext, _messageId);
+// }
+ // Old:
+ _store.removeMessage(storeContext, _messageId);
}
catch (AMQException e)
{
@@ -373,6 +489,11 @@ public class AMQMessage
public boolean checkToken(Object token)
{
+ if(_tokens==null)
+ {
+ _tokens = new HashSet<Object>();
+ }
+
if (_tokens.contains(token))
{
return true;
@@ -386,22 +507,17 @@ public class AMQMessage
public void enqueue(AMQQueue queue) throws AMQException
{
- //if the message is not persistent or the queue is not durable
- //we will not need to recover the association and so do not
- //need to record it
- if (isPersistent() && queue.isDurable())
- {
- _store.enqueueMessage(queue.getName(), _messageId);
- }
+ _destinationQueues.add(queue);
}
- public void dequeue(AMQQueue queue) throws AMQException
+ public void dequeue(StoreContext storeContext, AMQQueue queue) throws AMQException
{
+ _messageHandle.dequeue(storeContext, _messageId, queue);
//only record associations where both queue and message will survive
//a restart, so only need to remove association if this is the case
if (isPersistent() && queue.isDurable())
{
- _store.dequeueMessage(queue.getName(), _messageId);
+ _store.dequeueMessage(storeContext, queue.getName(), _messageId);
}
}
@@ -410,16 +526,6 @@ public class AMQMessage
return getDeliveryMode() == 2;
}
- public void setTxnBuffer(TxnBuffer buffer)
- {
- _txnBuffer = buffer;
- }
-
- public TxnBuffer getTxnBuffer()
- {
- return _txnBuffer;
- }
-
/**
* Called to enforce the 'immediate' flag.
* @throws NoConsumersException if the message is marked for
@@ -453,48 +559,82 @@ public class AMQMessage
return _deliveredToConsumer;
}
+ public boolean taken()
+ {
+ return _taken.getAndSet(true);
+ }
- public MessageDecorator getDecodedMessage(String type)
+ public void release()
{
- MessageDecorator msgtype = null;
+ _taken.set(false);
+ }
- if (_decodedMessages != null)
+ public void routingComplete(MessageStore store, StoreContext storeContext, MessageHandleFactory factory) throws AMQException
+ {
+ final boolean persistent = isPersistent();
+ _messageHandle = factory.createMessageHandle(_messageId, store, persistent);
+ if (persistent)
{
- msgtype = _decodedMessages.get(type);
-
- if (msgtype == null)
- {
- msgtype = decorateMessage(type);
- }
+ _txnContext.beginTranIfNecessary();
}
- return msgtype;
+ // enqueuing the messages ensure that if required the destinations are recorded to a
+ // persistent store
+ for (AMQQueue q : _destinationQueues)
+ {
+ _messageHandle.enqueue(storeContext, _messageId, q);
+ }
+ deliver(storeContext);
}
-
- private MessageDecorator decorateMessage(String type)
+
+ private void deliver(StoreContext storeContext) throws AMQException
{
- MessageDecorator msgdec = null;
-
- if (type.equals(JMS_MESSAGE))
+ // we get a reference to the destination queues now so that we can clear the
+ // transient message data as quickly as possible
+ if (_log.isDebugEnabled())
{
- msgdec = new JMSMessage(this);
+ _log.debug("Delivering message " + _messageId);
}
+ try
+ {
+ // first we allow the handle to know that the message has been fully received. This is useful if it is
+ // maintaining any calculated values based on content chunks
+ _messageHandle.setPublishAndContentHeaderBody(storeContext, _messageId, _transferBody);
+
+ // we then allow the transactional context to do something with the message content
+ // now that it has all been received, before we attempt delivery
+ _txnContext.messageFullyReceived(isPersistent());
- if (msgdec != null)
+ for (AMQQueue q : _destinationQueues)
+ {
+ _txnContext.deliver(this, q);
+ }
+ }
+ finally
{
- _decodedMessages.put(type, msgdec);
+ _destinationQueues.clear();
+ decrementReference(storeContext);
}
-
- return msgdec;
}
-
- public boolean taken()
+
+ // Robert Godfrey added these in r497770
+ public void writeDeliver(AMQProtocolSession protocolSession, int channelId, long deliveryTag, AMQShortString consumerTag)
+ throws AMQException
{
- return _taken.getAndSet(true);
+ throw new Error("XXX");
}
-
- public void release()
+ public void writeGetOk(AMQProtocolSession protocolSession, int channelId, long deliveryTag, int queueSize) throws AMQException
{
- _taken.set(false);
+ throw new Error("XXX");
+ }
+ private ByteBuffer createEncodedGetOkFrame(int channelId, long deliveryTag, int queueSize)
+ {
+ throw new Error("XXX");
}
+ // Robert Godfrey added these in r503604
+ public long getArrivalTime()
+ {
+ throw new Error("XXX");
+ }
+
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/AMQMessageHandle.java b/java/broker/src/main/java/org/apache/qpid/server/queue/AMQMessageHandle.java
new file mode 100644
index 0000000000..acf523a7d3
--- /dev/null
+++ b/java/broker/src/main/java/org/apache/qpid/server/queue/AMQMessageHandle.java
@@ -0,0 +1,74 @@
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+package org.apache.qpid.server.queue;
+
+import org.apache.qpid.AMQException;
+import org.apache.qpid.server.store.StoreContext;
+import org.apache.qpid.framing.MessageTransferBody;
+
+/**
+ * A pluggable way of getting message data. Implementations can provide intelligent caching for example or
+ * even no caching at all to minimise the broker memory footprint.
+ *
+ * The method all take a messageId to avoid having to store it in the instance - the AMQMessage container
+ * must already keen the messageId so it is pointless storing it twice.
+ */
+public interface AMQMessageHandle
+{
+ MessageTransferBody getContentHeaderBody(Long messageId) throws AMQException;
+
+ /**
+ * @return the number of body frames associated with this message
+ */
+ int getBodyCount(Long messageId) throws AMQException;
+
+ /**
+ * @return the size of the body
+ */
+ long getBodySize(Long messageId) throws AMQException;
+
+ /**
+ * Get a particular content body
+ * @param index the index of the body to retrieve, must be between 0 and getBodyCount() - 1
+ * @return a content body
+ * @throws IllegalArgumentException if the index is invalid
+ */
+ byte[] getContentBody(Long messageId, int index) throws IllegalArgumentException, AMQException;
+
+ void addContentBodyFrame(StoreContext storeContext, Long messageId, byte[] contentBody, boolean isLastContentBody) throws AMQException;
+
+ MessageTransferBody getPublishBody(Long messageId) throws AMQException;
+
+ boolean isRedelivered();
+
+ void setRedelivered(boolean redelivered);
+
+ boolean isPersistent(Long messageId) throws AMQException;
+
+ void setPublishAndContentHeaderBody(StoreContext storeContext, Long messageId, MessageTransferBody messageTransferBody)
+ throws AMQException;
+
+ void removeMessage(StoreContext storeContext, Long messageId) throws AMQException;
+
+ void enqueue(StoreContext storeContext, Long messageId, AMQQueue queue) throws AMQException;
+
+ void dequeue(StoreContext storeContext, Long messageId, AMQQueue queue) throws AMQException;
+}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueue.java b/java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueue.java
index cb7ec13c3e..a7c4b5ca19 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueue.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueue.java
@@ -7,9 +7,9 @@
* 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
@@ -23,16 +23,19 @@ package org.apache.qpid.server.queue;
import org.apache.log4j.Logger;
import org.apache.qpid.AMQException;
import org.apache.qpid.framing.FieldTable;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.server.exchange.Exchange;
import org.apache.qpid.server.management.Managable;
import org.apache.qpid.server.management.ManagedObject;
import org.apache.qpid.server.protocol.AMQProtocolSession;
-import org.apache.qpid.server.txn.TxnBuffer;
-import org.apache.qpid.server.txn.TxnOp;
+import org.apache.qpid.server.store.StoreContext;
+import org.apache.qpid.server.AMQChannel;
+import org.apache.qpid.server.virtualhost.VirtualHost;
import javax.management.JMException;
import java.text.MessageFormat;
import java.util.List;
+import java.util.ArrayList;
import java.util.concurrent.Executor;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
@@ -68,12 +71,12 @@ public class AMQQueue implements Managable, Comparable
private static final Logger _logger = Logger.getLogger(AMQQueue.class);
- private final String _name;
+ private final AMQShortString _name;
/**
* null means shared
*/
- private final String _owner;
+ private final AMQShortString _owner;
private final boolean _durable;
@@ -105,11 +108,6 @@ public class AMQQueue implements Managable, Comparable
private final DeliveryManager _deliveryMgr;
/**
- * The queue registry with which this queue is registered.
- */
- private final QueueRegistry _queueRegistry;
-
- /**
* Used to track bindings to exchanges so that on deletion they can easily
* be cancelled.
*/
@@ -122,6 +120,9 @@ public class AMQQueue implements Managable, Comparable
private final AMQQueueMBean _managedObject;
+ private final VirtualHost _virtualHost;
+
+
/**
* max allowed size(KB) of a single message
*/
@@ -147,60 +148,27 @@ public class AMQQueue implements Managable, Comparable
return _name.compareTo(((AMQQueue) o).getName());
}
- public AMQQueue(String name, boolean durable, String owner,
- boolean autoDelete, QueueRegistry queueRegistry)
+ public AMQQueue(AMQShortString name, boolean durable, AMQShortString owner,
+ boolean autoDelete, VirtualHost virtualHost)
throws AMQException
{
- this(name, durable, owner, autoDelete, queueRegistry,
- AsyncDeliveryConfig.getAsyncDeliveryExecutor(), new SubscriptionImpl.Factory());
+ this(name, durable, owner, autoDelete, virtualHost,
+ AsyncDeliveryConfig.getAsyncDeliveryExecutor(), new SubscriptionSet(), new SubscriptionImpl.Factory());
}
- public AMQQueue(String name, boolean durable, String owner,
- boolean autoDelete, QueueRegistry queueRegistry, SubscriptionFactory subscriptionFactory)
- throws AMQException
- {
- this(name, durable, owner, autoDelete, queueRegistry,
- AsyncDeliveryConfig.getAsyncDeliveryExecutor(), subscriptionFactory);
- }
- public AMQQueue(String name, boolean durable, String owner,
- boolean autoDelete, QueueRegistry queueRegistry, Executor asyncDelivery,
- SubscriptionFactory subscriptionFactory)
- throws AMQException
- {
- this(name, durable, owner, autoDelete, queueRegistry, asyncDelivery, new SubscriptionSet(), subscriptionFactory);
- }
-
- public AMQQueue(String name, boolean durable, String owner,
- boolean autoDelete, QueueRegistry queueRegistry, Executor asyncDelivery)
- throws AMQException
- {
-
- this(name, durable, owner, autoDelete, queueRegistry, asyncDelivery, new SubscriptionSet(),
- new SubscriptionImpl.Factory());
- }
-
- protected AMQQueue(String name, boolean durable, String owner,
- boolean autoDelete, QueueRegistry queueRegistry,
- SubscriptionSet subscribers, SubscriptionFactory subscriptionFactory)
- throws AMQException
- {
- this(name, durable, owner, autoDelete, queueRegistry,
- AsyncDeliveryConfig.getAsyncDeliveryExecutor(), subscribers, subscriptionFactory);
- }
-
- protected AMQQueue(String name, boolean durable, String owner,
- boolean autoDelete, QueueRegistry queueRegistry,
+ protected AMQQueue(AMQShortString name, boolean durable, AMQShortString owner,
+ boolean autoDelete, VirtualHost virtualHost,
SubscriptionSet subscribers)
throws AMQException
{
- this(name, durable, owner, autoDelete, queueRegistry,
+ this(name, durable, owner, autoDelete, virtualHost,
AsyncDeliveryConfig.getAsyncDeliveryExecutor(), subscribers, new SubscriptionImpl.Factory());
}
- protected AMQQueue(String name, boolean durable, String owner,
- boolean autoDelete, QueueRegistry queueRegistry,
+ protected AMQQueue(AMQShortString name, boolean durable, AMQShortString owner,
+ boolean autoDelete, VirtualHost virtualHost,
Executor asyncDelivery, SubscriptionSet subscribers, SubscriptionFactory subscriptionFactory)
throws AMQException
{
@@ -208,45 +176,23 @@ public class AMQQueue implements Managable, Comparable
{
throw new IllegalArgumentException("Queue name must not be null");
}
- if (queueRegistry == null)
+ if (virtualHost == null)
{
- throw new IllegalArgumentException("Queue registry must not be null");
+ throw new IllegalArgumentException("Virtual Host must not be null");
}
_name = name;
_durable = durable;
_owner = owner;
_autoDelete = autoDelete;
- _queueRegistry = queueRegistry;
+ _virtualHost = virtualHost;
_asyncDelivery = asyncDelivery;
+
_managedObject = createMBean();
_managedObject.register();
+
_subscribers = subscribers;
_subscriptionFactory = subscriptionFactory;
-
- //fixme - Make this configurable via the broker config.xml
- if (System.getProperties().getProperty("deliverymanager") != null)
- {
- if (System.getProperties().getProperty("deliverymanager").equals("ConcurrentSelectorDeliveryManager"))
- {
- _logger.info("Using ConcurrentSelectorDeliveryManager");
- _deliveryMgr = new ConcurrentSelectorDeliveryManager(_subscribers, this);
- }
- else if (System.getProperties().getProperty("deliverymanager").equals("ConcurrentDeliveryManager"))
- {
- _logger.info("Using ConcurrentDeliveryManager");
- _deliveryMgr = new ConcurrentDeliveryManager(_subscribers, this);
- }
- else
- {
- _logger.info("Using SynchronizedDeliveryManager");
- _deliveryMgr = new SynchronizedDeliveryManager(_subscribers, this);
- }
- }
- else
- {
- _logger.info("Using Default DeliveryManager: ConcurrentSelectorDeliveryManager");
- _deliveryMgr = new ConcurrentSelectorDeliveryManager(_subscribers, this);
- }
+ _deliveryMgr = new ConcurrentSelectorDeliveryManager(_subscribers, this);
}
private AMQQueueMBean createMBean() throws AMQException
@@ -261,7 +207,7 @@ public class AMQQueue implements Managable, Comparable
}
}
- public String getName()
+ public AMQShortString getName()
{
return _name;
}
@@ -276,7 +222,7 @@ public class AMQQueue implements Managable, Comparable
return _durable;
}
- public String getOwner()
+ public AMQShortString getOwner()
{
return _owner;
}
@@ -302,6 +248,12 @@ public class AMQQueue implements Managable, Comparable
return _deliveryMgr.getMessages();
}
+ public long getQueueDepth()
+ {
+ return _deliveryMgr.getTotalMessageSize();
+ }
+
+
/**
* @param messageId
* @return AMQMessage with give id if exists. null if AMQMessage with given id doesn't exist.
@@ -365,13 +317,13 @@ public class AMQQueue implements Managable, Comparable
_maxMessageCount = value;
}
- public Long getMaximumQueueDepth()
+ public long getMaximumQueueDepth()
{
return _maxQueueDepth;
}
// Sets the queue depth, the max queue size
- public void setMaximumQueueDepth(Long value)
+ public void setMaximumQueueDepth(long value)
{
_maxQueueDepth = value;
}
@@ -379,25 +331,25 @@ public class AMQQueue implements Managable, Comparable
/**
* Removes the AMQMessage from the top of the queue.
*/
- public void deleteMessageFromTop() throws AMQException
+ public void deleteMessageFromTop(StoreContext storeContext) throws AMQException
{
- _deliveryMgr.removeAMessageFromTop();
+ _deliveryMgr.removeAMessageFromTop(storeContext);
}
/**
* removes all the messages from the queue.
*/
- public long clearQueue() throws AMQException
+ public long clearQueue(StoreContext storeContext) throws AMQException
{
- return _deliveryMgr.clearAllMessages();
+ return _deliveryMgr.clearAllMessages(storeContext);
}
- public void bind(String routingKey, Exchange exchange)
+ public void bind(AMQShortString routingKey, Exchange exchange)
{
_bindings.addBinding(routingKey, exchange);
}
- public void registerProtocolSession(AMQProtocolSession ps, int channel, String consumerTag, boolean acks,
+ public void registerProtocolSession(AMQProtocolSession ps, int channel, AMQShortString consumerTag, boolean acks,
FieldTable filters, boolean noLocal, boolean exclusive)
throws AMQException
{
@@ -413,6 +365,24 @@ public class AMQQueue implements Managable, Comparable
decrementSubscriberCount();
throw EXISTING_SUBSCRIPTION;
}
+ }
+ else if(exclusive)
+ {
+ setExclusive(true);
+ }
+
+ if(incrementSubscriberCount() > 1)
+ {
+ if(isExclusive())
+ {
+ decrementSubscriberCount();
+ throw EXISTING_EXCLUSIVE;
+ }
+ else if(exclusive)
+ {
+ decrementSubscriberCount();
+ throw EXISTING_SUBSCRIPTION;
+ }
}
else if(exclusive)
@@ -455,7 +425,7 @@ public class AMQQueue implements Managable, Comparable
return _subscriberCount.decrementAndGet();
}
- public void unregisterProtocolSession(AMQProtocolSession ps, int channel, String consumerTag) throws AMQException
+ public void unregisterProtocolSession(AMQProtocolSession ps, int channel, AMQShortString consumerTag) throws AMQException
{
debug("Unregistering protocol session {0} with channel {1} and consumer tag {2} from {3}", ps, channel, consumerTag,
this);
@@ -520,7 +490,7 @@ public class AMQQueue implements Managable, Comparable
{
_subscribers.queueDeleted(this);
_bindings.deregister();
- _queueRegistry.unregisterQueue(_name);
+ _virtualHost.getQueueRegistry().unregisterQueue(_name);
_managedObject.unregister();
for(Task task : _deleteTaskList)
{
@@ -528,7 +498,6 @@ public class AMQQueue implements Managable, Comparable
}
_deleteTaskList.clear();
}
-
}
protected void autodelete() throws AMQException
@@ -536,31 +505,27 @@ public class AMQQueue implements Managable, Comparable
debug("autodeleting {0}", this);
delete();
}
-
- public void deliver(AMQMessage msg) throws AMQException
+
+ public void processGet(StoreContext storeContext, AMQMessage msg) throws AMQException
{
- TxnBuffer buffer = msg.getTxnBuffer();
- if (buffer == null)
+ _deliveryMgr.deliver(storeContext, getName(), msg);
+ try
{
- //non-transactional
- record(msg);
- process(msg);
+ msg.checkDeliveredToConsumer();
+ updateReceivedMessageCount(msg);
}
- else
+ catch (NoConsumersException e)
{
- buffer.enlist(new Deliver(msg));
+ // as this message will be returned, it should be removed
+ // from the queue:
+ dequeue(storeContext, msg);
}
}
- private void record(AMQMessage msg) throws AMQException
- {
- msg.enqueue(this);
- msg.incrementReference();
- }
- private void process(AMQMessage msg) throws FailedDequeueException
+ public void process(StoreContext storeContext, AMQMessage msg) throws AMQException
{
- _deliveryMgr.deliver(getName(), msg);
+ _deliveryMgr.deliver(storeContext, getName(), msg);
try
{
msg.checkDeliveredToConsumer();
@@ -570,16 +535,16 @@ public class AMQQueue implements Managable, Comparable
{
// as this message will be returned, it should be removed
// from the queue:
- dequeue(msg);
+ dequeue(storeContext, msg);
}
}
- void dequeue(AMQMessage msg) throws FailedDequeueException
+ void dequeue(StoreContext storeContext, AMQMessage msg) throws FailedDequeueException
{
try
{
- msg.dequeue(this);
- msg.decrementReference();
+ msg.dequeue(storeContext, this);
+ msg.decrementReference(storeContext);
}
catch (MessageCleanupException e)
{
@@ -591,7 +556,7 @@ public class AMQQueue implements Managable, Comparable
}
catch (AMQException e)
{
- throw new FailedDequeueException(_name, e);
+ throw new FailedDequeueException(_name.toString(), e);
}
}
@@ -605,10 +570,17 @@ public class AMQQueue implements Managable, Comparable
return _subscribers;
}
- protected void updateReceivedMessageCount(AMQMessage msg)
+ protected void updateReceivedMessageCount(AMQMessage msg) throws AMQException
{
_totalMessagesReceived++;
- _managedObject.checkForNotification(msg);
+ try
+ {
+ _managedObject.checkForNotification(msg);
+ }
+ catch (JMException e)
+ {
+ throw new AMQException("Unable to get notification from manage queue: " + e, e);
+ }
}
public boolean equals(Object o)
@@ -645,44 +617,19 @@ public class AMQQueue implements Managable, Comparable
}
}
- private class Deliver implements TxnOp
+ public boolean performGet(AMQProtocolSession session, AMQChannel channel, boolean acks) throws AMQException
{
- private final AMQMessage _msg;
-
- Deliver(AMQMessage msg)
- {
- _msg = msg;
- }
-
- public void prepare() throws AMQException
- {
- //do the persistent part of the record()
- _msg.enqueue(AMQQueue.this);
- }
-
- public void undoPrepare()
- {
- }
+ return _deliveryMgr.performGet(session, channel, acks);
+ }
- public void commit()
- {
- //do the memeory part of the record()
- _msg.incrementReference();
- //then process the message
- try
- {
- process(_msg);
- }
- catch (FailedDequeueException e)
- {
- //TODO: is there anything else we can do here? I think not...
- _logger.error("Error during commit of a queue delivery: " + e, e);
- }
- }
+ public QueueRegistry getQueueRegistry()
+ {
+ return _virtualHost.getQueueRegistry();
+ }
- public void rollback()
- {
- }
+ public VirtualHost getVirtualHost()
+ {
+ return _virtualHost;
}
public static interface Task
@@ -694,5 +641,4 @@ public class AMQQueue implements Managable, Comparable
{
_deleteTaskList.add(task);
}
-
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueueMBean.java b/java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueueMBean.java
index d3d52cd627..9aafe95bb0 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueueMBean.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueueMBean.java
@@ -17,19 +17,19 @@
*/
package org.apache.qpid.server.queue;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.framing.FieldTable;
import org.apache.qpid.server.management.MBeanDescription;
import org.apache.qpid.server.management.AMQManagedObject;
import org.apache.qpid.server.management.MBeanConstructor;
+import org.apache.qpid.server.management.ManagedObject;
+import org.apache.qpid.server.store.StoreContext;
+import org.apache.qpid.server.Main;
import org.apache.qpid.AMQException;
import org.apache.mina.common.ByteBuffer;
import javax.management.openmbean.*;
-import javax.management.JMException;
-import javax.management.Notification;
-import javax.management.MBeanException;
-import javax.management.MBeanNotificationInfo;
-import javax.management.OperationsException;
+import javax.management.*;
import javax.management.monitor.MonitorNotification;
import java.util.ArrayList;
@@ -37,6 +37,7 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
+import java.util.Iterator;
/**
* MBean class for AMQQueue. It implements all the management features exposed
@@ -45,19 +46,25 @@ import java.util.Set;
@MBeanDescription("Management Interface for AMQQueue")
public class AMQQueueMBean extends AMQManagedObject implements ManagedQueue
{
+ /**
+ * Since the MBean is not associated with a real channel we can safely create our own store context
+ * for use in the few methods that require one.
+ */
+ private StoreContext _storeContext = new StoreContext();
+
private AMQQueue _queue = null;
private String _queueName = null;
// OpenMBean data types for viewMessages method
- private String[] _msgAttributeNames = {"Message Id", "Header", "Size(bytes)", "Redelivered"};
- private String[] _msgAttributeIndex = {_msgAttributeNames[0]};
- private OpenType[] _msgAttributeTypes = new OpenType[4]; // AMQ message attribute types.
- private CompositeType _messageDataType = null; // Composite type for representing AMQ Message data.
- private TabularType _messagelistDataType = null; // Datatype for representing AMQ messages list.
+ private final static String[] _msgAttributeNames = {"AMQ MessageId", "Header", "Size(bytes)", "Redelivered"};
+ private static String[] _msgAttributeIndex = {_msgAttributeNames[0]};
+ private static OpenType[] _msgAttributeTypes = new OpenType[4]; // AMQ message attribute types.
+ private static CompositeType _messageDataType = null; // Composite type for representing AMQ Message data.
+ private static TabularType _messagelistDataType = null; // Datatype for representing AMQ messages list.
// OpenMBean data types for viewMessageContent method
- private CompositeType _msgContentType = null;
- private String[] _msgContentAttributes = {"Message Id", "MimeType", "Encoding", "Content"};
- private OpenType[] _msgContentAttributeTypes = new OpenType[4];
+ private static CompositeType _msgContentType = null;
+ private final static String[] _msgContentAttributes = {"AMQ MessageId", "MimeType", "Encoding", "Content"};
+ private static OpenType[] _msgContentAttributeTypes = new OpenType[4];
@MBeanConstructor("Creates an MBean exposing an AMQQueue")
public AMQQueueMBean(AMQQueue queue) throws JMException
@@ -65,13 +72,31 @@ public class AMQQueueMBean extends AMQManagedObject implements ManagedQueue
super(ManagedQueue.class, ManagedQueue.TYPE);
_queue = queue;
_queueName = jmxEncode(new StringBuffer(queue.getName()), 0).toString();
- init();
+ }
+
+
+ public ManagedObject getParentObject()
+ {
+ return _queue.getVirtualHost().getManagedObject();
+ }
+
+ static
+ {
+ try
+ {
+ init();
+ }
+ catch(JMException ex)
+ {
+ // It should never occur
+ System.out.println(ex.getMessage());
+ }
}
/**
* initialises the openmbean data types
*/
- private void init() throws OpenDataException
+ private static void init() throws OpenDataException
{
_msgContentAttributeTypes[0] = SimpleType.LONG; // For message id
_msgContentAttributeTypes[1] = SimpleType.STRING; // For MimeType
@@ -106,7 +131,7 @@ public class AMQQueueMBean extends AMQManagedObject implements ManagedQueue
public String getOwner()
{
- return _queue.getOwner();
+ return String.valueOf(_queue.getOwner());
}
public boolean isAutoDelete()
@@ -167,26 +192,21 @@ public class AMQQueueMBean extends AMQManagedObject implements ManagedQueue
/**
* returns the size of messages(KB) in the queue.
*/
- public Long getQueueDepth()
+ public Long getQueueDepth() throws JMException
{
- List<AMQMessage> list = _queue.getMessagesOnTheQueue();
- if (list.size() == 0)
- {
- return 0l;
- }
+ return getQueueDepthKb();
+ }
- long queueDepth = 0;
- for (AMQMessage message : list)
- {
- queueDepth = queueDepth + getMessageSize(message);
- }
- return (long) Math.round(queueDepth / 1000);
+ public long getQueueDepthKb()
+ {
+ long queueBytesSize = _queue.getQueueDepth();
+ return queueBytesSize >> 10 ;
}
/**
* returns size of message in bytes
*/
- private long getMessageSize(AMQMessage msg)
+ private long getMessageSize(AMQMessage msg) throws AMQException
{
if (msg == null)
{
@@ -199,7 +219,7 @@ public class AMQQueueMBean extends AMQManagedObject implements ManagedQueue
/**
* Checks if there is any notification to be send to the listeners
*/
- public void checkForNotification(AMQMessage msg)
+ public void checkForNotification(AMQMessage msg) throws AMQException, JMException
{
// Check for threshold message count
Integer msgCount = getMessageCount();
@@ -216,7 +236,7 @@ public class AMQQueueMBean extends AMQManagedObject implements ManagedQueue
}
// Check for threshold queue depth in bytes
- long queueDepth = getQueueDepth();
+ long queueDepth = getQueueDepthKb();
if (queueDepth >= _queue.getMaximumQueueDepth())
{
notifyClients("Queue depth(" + queueDepth + "), Queue size has reached the threshold high value");
@@ -235,13 +255,13 @@ public class AMQQueueMBean extends AMQManagedObject implements ManagedQueue
}
/**
- * @see org.apache.qpid.server.queue.AMQQueue#deleteMessageFromTop()
+ * @see org.apache.qpid.server.queue.AMQQueue#deleteMessageFromTop
*/
public void deleteMessageFromTop() throws JMException
{
try
{
- _queue.deleteMessageFromTop();
+ _queue.deleteMessageFromTop(_storeContext);
}
catch (AMQException ex)
{
@@ -250,13 +270,13 @@ public class AMQQueueMBean extends AMQManagedObject implements ManagedQueue
}
/**
- * @see org.apache.qpid.server.queue.AMQQueue#clearQueue()
+ * @see org.apache.qpid.server.queue.AMQQueue#clearQueue
*/
public void clearQueue() throws JMException
{
try
{
- _queue.clearQueue();
+ _queue.clearQueue(_storeContext);
}
catch (AMQException ex)
{
@@ -278,13 +298,14 @@ public class AMQQueueMBean extends AMQManagedObject implements ManagedQueue
// get message content
byte[] bytes = msg.getMessageBytes();
Byte[] msgContent = new Byte[bytes.length];
- for (int i = 0; i < bytes.length; i++) {
+ for (int i = 0; i < bytes.length; i++)
+ {
msgContent[i] = Byte.valueOf(bytes[i]);
}
// Create header attributes list
- String mimeType = msg.getContentType();
- String encoding = msg.getEncoding();
+ AMQShortString mimeType = msg.getContentType();
+ AMQShortString encoding = msg.getContentEncoding();
Object[] itemValues = {msgId, mimeType, encoding, msgContent};
return new CompositeDataSupport(_msgContentType, _msgContentAttributes, itemValues);
@@ -295,7 +316,7 @@ public class AMQQueueMBean extends AMQManagedObject implements ManagedQueue
hdrs.put("Reply-To", msg.getReplyTo());
hdrs.put("Application-Id", msg.getAppId());
hdrs.put("User-Id", msg.getUserId());
- hdrs.put("Message-Id", msg.getXXXMessageId());
+ hdrs.put("Message-Id", msg.getMessageId());
hdrs.put("Correlation-Id", msg.getCorrelationId());
hdrs.put("DeliveryMode", msg.getDeliveryMode());
hdrs.put("Expiration", msg.getExpiration());
@@ -319,25 +340,41 @@ public class AMQQueueMBean extends AMQManagedObject implements ManagedQueue
List<AMQMessage> list = _queue.getMessagesOnTheQueue();
TabularDataSupport _messageList = new TabularDataSupport(_messagelistDataType);
- // Create the tabular list of message header contents
- for (int i = beginIndex; i <= endIndex && i <= list.size(); i++)
+// try
{
- AMQMessage msg = list.get(i - 1);
- // Create header attributes list
- Map headers = getHeaders(msg);
- Set<String> names = headers.keySet();
- String[] values = new String[names.size()];
- int index = 0;
- for (String name : names) {
- values[index++] = "" + headers.get(name);
+ // Create the tabular list of message header contents
+ for (int i = beginIndex; i <= endIndex && i <= list.size(); i++)
+ {
+ AMQMessage msg = list.get(i - 1);
+ // Create header attributes list
+ Map headers = getHeaders(msg);
+ Set<String> names = headers.keySet();
+ String[] values = new String[names.size()];
+ int index = 0;
+ for (String name : names)
+ {
+ values[index++] = "" + headers.get(name);
+ }
+ Object[] itemValues = {msg.getMessageId(), values, msg.getSize(), msg.isRedelivered()};
+ CompositeData messageData = new CompositeDataSupport(_messageDataType, _msgAttributeNames, itemValues);
+ _messageList.put(messageData);
}
- Object[] itemValues = {msg.getMessageId(), values, msg.getSize(), msg.isRedelivered()};
- CompositeData messageData = new CompositeDataSupport(_messageDataType, _msgAttributeNames, itemValues);
- _messageList.put(messageData);
}
+// catch (AMQException e)
+// {
+// throw new JMException("Error creating message contents: " + e);
+// }
return _messageList;
}
+//
+// public ObjectName getObjectName() throws MalformedObjectNameException
+// {
+// String objNameString = super.getObjectName().toString();
+//
+// return new ObjectName(objNameString);
+// }
+
/**
* returns Notifications sent by this MBean.
@@ -353,4 +390,4 @@ public class AMQQueueMBean extends AMQManagedObject implements ManagedQueue
return new MBeanNotificationInfo[]{info1};
}
-} // End of AMQMBean class
+} // End of AMQQueueMBean class
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/AMQReference.java b/java/broker/src/main/java/org/apache/qpid/server/queue/AMQReference.java
new file mode 100644
index 0000000000..a852d0af64
--- /dev/null
+++ b/java/broker/src/main/java/org/apache/qpid/server/queue/AMQReference.java
@@ -0,0 +1,97 @@
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+package org.apache.qpid.server.queue;
+
+import org.apache.qpid.AMQException;
+import org.apache.qpid.server.queue.AMQMessage;
+import org.apache.qpid.server.store.StoreContext;
+
+import org.apache.mina.common.ByteBuffer;
+
+import java.util.LinkedList;
+import java.util.List;
+
+/**
+ * This class agregates a message reference, which consists of
+ * acculated content and one or more transfers to which it will
+ * be routed.
+ */
+public class AMQReference
+{
+ private byte[] ref;
+ private static List<AMQMessage> messageList = new LinkedList();
+ private static List<ByteBuffer> contentList = new LinkedList();
+
+ public AMQReference(byte[] ref)
+ {
+ this.ref = ref;
+ }
+
+ public byte[] getReference()
+ {
+ return ref;
+ }
+
+ public String getReferenceAsString()
+ {
+ return new String(ref);
+ }
+
+ public void addRefTransferBody(AMQMessage msg)
+ {
+ messageList.add(msg);
+ }
+
+ public List<AMQMessage> getMessageList()
+ {
+ return messageList;
+ }
+
+ public void appendContent(ByteBuffer content)
+ {
+ contentList.add(content);
+ }
+
+ public List<ByteBuffer> getContentList()
+ {
+ return contentList;
+ }
+
+ public long totalContentLength()
+ {
+ long tot = 0L;
+ for (ByteBuffer bb : contentList)
+ {
+ tot += bb.limit();
+ }
+ return tot;
+ }
+
+ public void close(StoreContext storeContext) throws AMQException
+ {
+ throw new Error("XXX");
+ }
+
+ public String toString()
+ {
+ return "AMQReference " + getReferenceAsString() + ": Num messages=" + messageList.size() + "; Num contents=" + contentList.size() + "; Tot content length=" + totalContentLength();
+ }
+}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/ConcurrentDeliveryManager.java b/java/broker/src/main/java/org/apache/qpid/server/queue/ConcurrentDeliveryManager.java
deleted file mode 100644
index 560b881ee3..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/ConcurrentDeliveryManager.java
+++ /dev/null
@@ -1,363 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.queue;
-
-import org.apache.log4j.Logger;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.util.ConcurrentLinkedQueueAtomicSize;
-import org.apache.qpid.configuration.Configured;
-import org.apache.qpid.server.configuration.Configurator;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Queue;
-import java.util.concurrent.Executor;
-import java.util.concurrent.locks.ReentrantLock;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-
-/**
- * Manages delivery of messages on behalf of a queue
- */
-public class ConcurrentDeliveryManager implements DeliveryManager
-{
- private static final Logger _log = Logger.getLogger(ConcurrentDeliveryManager.class);
-
- @Configured(path = "advanced.compressBufferOnQueue",
- defaultValue = "false")
- public boolean compressBufferOnQueue;
- /**
- * Holds any queued messages
- */
- private final Queue<AMQMessage> _messages = new ConcurrentLinkedQueueAtomicSize<AMQMessage>();
- //private int _messageCount;
- /**
- * Ensures that only one asynchronous task is running for this manager at
- * any time.
- */
- private final AtomicBoolean _processing = new AtomicBoolean();
- /**
- * The subscriptions on the queue to whom messages are delivered
- */
- private final SubscriptionManager _subscriptions;
-
- /**
- * A reference to the queue we are delivering messages for. We need this to be able
- * to pass the code that handles acknowledgements a handle on the queue.
- */
- private final AMQQueue _queue;
-
-
- /**
- * Lock used to ensure that an channel that becomes unsuspended during the start of the queueing process is forced
- * to wait till the first message is added to the queue. This will ensure that the _queue has messages to be delivered
- * via the async thread.
- * <p/>
- * Lock is used to control access to hasQueuedMessages() and over the addition of messages to the queue.
- */
- private ReentrantLock _lock = new ReentrantLock();
-
-
- ConcurrentDeliveryManager(SubscriptionManager subscriptions, AMQQueue queue)
- {
-
- //Set values from configuration
- Configurator.configure(this);
-
- if (compressBufferOnQueue)
- {
- _log.info("Compressing Buffers on queue.");
- }
-
- _subscriptions = subscriptions;
- _queue = queue;
- }
-
- /**
- * @return boolean if we are queueing
- */
- private boolean queueing()
- {
- return hasQueuedMessages();
- }
-
-
- /**
- * @param msg to enqueue
- * @return true if we are queue this message
- */
- private boolean enqueue(AMQMessage msg)
- {
- if (msg.isImmediate())
- {
- return false;
- }
- else
- {
- _lock.lock();
- try
- {
- if (queueing())
- {
- return addMessageToQueue(msg);
- }
- else
- {
- return false;
- }
- }
- finally
- {
- _lock.unlock();
- }
- }
- }
-
- private void startQueueing(AMQMessage msg)
- {
- if (!msg.isImmediate())
- {
- addMessageToQueue(msg);
- }
- }
-
- private boolean addMessageToQueue(AMQMessage msg)
- {
- // XXX: I don't think this will have an effect anymore because
- // we don't allocate anymore space than we need. Also this
- // seems like an odd place to do this. Why wouldn't we want to
- // do this from a more central location on receiving the
- // message?
-
- // Shrink the ContentBodies to their actual size to save memory.
- /*if (compressBufferOnQueue)
- {
- Iterator it = msg.getContentBodies().iterator();
- while (it.hasNext())
- {
- ContentBody cb = (ContentBody) it.next();
- cb.reduceBufferToFit();
- }
- }*/
-
- _messages.offer(msg);
-
- return true;
- }
-
-
- public boolean hasQueuedMessages()
- {
-
- _lock.lock();
- try
- {
- return !_messages.isEmpty();
- }
- finally
- {
- _lock.unlock();
- }
-
-
- }
-
- public int getQueueMessageCount()
- {
- return getMessageCount();
- }
-
- /**
- * This is an EXPENSIVE opperation to perform with a ConcurrentLinkedQueue as it must run the queue to determine size.
- * The ConcurrentLinkedQueueAtomicSize uses an AtomicInteger to record the number of elements on the queue.
- *
- * @return int the number of messages in the delivery queue.
- */
- private int getMessageCount()
- {
- return _messages.size();
- }
-
-
- public synchronized List<AMQMessage> getMessages()
- {
- return new ArrayList<AMQMessage>(_messages);
- }
-
- public void populatePreDeliveryQueue(Subscription subscription)
- {
- //no-op . This DM has no PreDeliveryQueues
- }
-
- public synchronized void removeAMessageFromTop() throws AMQException
- {
- AMQMessage msg = poll();
- if (msg != null)
- {
- msg.dequeue(_queue);
- }
- }
-
- public synchronized long clearAllMessages() throws AMQException
- {
- AMQMessage msg = poll();
- while (msg != null)
- {
- msg.dequeue(_queue);
- msg = poll();
- }
- return 0;
- }
-
- /**
- * Only one thread should ever execute this method concurrently, but
- * it can do so while other threads invoke deliver().
- */
- private void processQueue()
- {
- try
- {
- boolean hasSubscribers = _subscriptions.hasActiveSubscribers();
- AMQMessage message = peek();
-
- //While we have messages to send and subscribers to send them to.
- while (message != null && hasSubscribers)
- {
- // _log.debug("Have messages(" + _messages.size() + ") and subscribers");
- Subscription next = _subscriptions.nextSubscriber(message);
- //FIXME Is there still not the chance that this subscribe could be suspended between here and the send?
-
- //We don't synchronize access to subscribers so need to re-check
- if (next != null)
- {
- next.send(message, _queue);
- poll();
- message = peek();
- }
- else
- {
- hasSubscribers = false;
- }
- }
- }
- catch (FailedDequeueException e)
- {
- _log.error("Unable to deliver message as dequeue failed: " + e, e);
- }
- finally
- {
- _log.debug("End of processQueue: (" + getQueueMessageCount() + ")" + " subscribers:" + _subscriptions.hasActiveSubscribers());
- }
- }
-
- private AMQMessage peek()
- {
- return _messages.peek();
- }
-
- private AMQMessage poll()
- {
- return _messages.poll();
- }
-
- Runner asyncDelivery = new Runner();
-
- public void processAsync(Executor executor)
- {
- _log.debug("Processing Async. Queued:" + hasQueuedMessages() + "(" + getQueueMessageCount() + ")" +
- " Active:" + _subscriptions.hasActiveSubscribers() +
- " Processing:" + _processing.get());
-
- if (hasQueuedMessages() && _subscriptions.hasActiveSubscribers())
- {
- //are we already running? if so, don't re-run
- if (_processing.compareAndSet(false, true))
- {
- // Do we need this?
- // This executor is created via Executors in AsyncDeliveryConfig which only returns a TPE so cast is ok.
- //if (executor != null && !((ThreadPoolExecutor) executor).isShutdown())
- {
- executor.execute(asyncDelivery);
- }
- }
- }
- }
-
- public void deliver(String name, AMQMessage msg) throws FailedDequeueException
- {
- // first check whether we are queueing, and enqueue if we are
- if (!enqueue(msg))
- {
- // not queueing so deliver message to 'next' subscriber
- _lock.lock();
- try
- {
- Subscription s = _subscriptions.nextSubscriber(msg);
- if (s == null)
- {
- if (!msg.isImmediate())
- {
- // no subscribers yet so enter 'queueing' mode and queue this message
- startQueueing(msg);
- }
- }
- else
- {
- s.send(msg, _queue);
- }
- }
- finally
- {
- _lock.unlock();
- }
- }
- }
-
- private class Runner implements Runnable
- {
- public void run()
- {
- boolean running = true;
- while (running)
- {
- processQueue();
-
- //Check that messages have not been added since we did our last peek();
- // Synchronize with the thread that adds to the queue.
- // If the queue is still empty then we can exit
- _lock.lock();
- try
- {
- if (!(hasQueuedMessages() && _subscriptions.hasActiveSubscribers()))
- {
- running = false;
- _processing.set(false);
- }
- }
- finally
- {
- _lock.unlock();
- }
- }
- }
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/ConcurrentSelectorDeliveryManager.java b/java/broker/src/main/java/org/apache/qpid/server/queue/ConcurrentSelectorDeliveryManager.java
index 5b3bf2bbeb..685015226c 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/ConcurrentSelectorDeliveryManager.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/queue/ConcurrentSelectorDeliveryManager.java
@@ -24,7 +24,11 @@ import org.apache.log4j.Logger;
import org.apache.qpid.AMQException;
import org.apache.qpid.util.ConcurrentLinkedQueueAtomicSize;
import org.apache.qpid.configuration.Configured;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.server.configuration.Configurator;
+import org.apache.qpid.server.store.StoreContext;
+import org.apache.qpid.server.AMQChannel;
+import org.apache.qpid.server.protocol.AMQProtocolSession;
import java.util.ArrayList;
import java.util.Iterator;
@@ -33,6 +37,7 @@ import java.util.Queue;
import java.util.concurrent.Executor;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
/**
@@ -49,6 +54,9 @@ public class ConcurrentSelectorDeliveryManager implements DeliveryManager
* Holds any queued messages
*/
private final Queue<AMQMessage> _messages = new ConcurrentLinkedQueueAtomicSize<AMQMessage>();
+
+ private final ReentrantLock _messageAccessLock = new ReentrantLock();
+
//private int _messageCount;
/**
* Ensures that only one asynchronous task is running for this manager at
@@ -75,6 +83,7 @@ public class ConcurrentSelectorDeliveryManager implements DeliveryManager
* Lock is used to control access to hasQueuedMessages() and over the addition of messages to the queue.
*/
private ReentrantLock _lock = new ReentrantLock();
+ private AtomicLong _totalMessageSize = new AtomicLong();
ConcurrentSelectorDeliveryManager(SubscriptionManager subscriptions, AMQQueue queue)
@@ -99,16 +108,18 @@ public class ConcurrentSelectorDeliveryManager implements DeliveryManager
// XXX
/*if (compressBufferOnQueue)
{
- Iterator it = msg.getContentBodies().iterator();
+ Iterator<ContentBody> it = msg.getContentBodyIterator();
while (it.hasNext())
{
- ContentBody cb = (ContentBody) it.next();
+ ContentBody cb = it.next();
cb.reduceBufferToFit();
}
}*/
_messages.offer(msg);
+ _totalMessageSize.addAndGet(msg.getSize());
+
return true;
}
@@ -143,6 +154,13 @@ public class ConcurrentSelectorDeliveryManager implements DeliveryManager
}
+
+ public long getTotalMessageSize()
+ {
+ return _totalMessageSize.get();
+ }
+
+
public synchronized List<AMQMessage> getMessages()
{
return new ArrayList<AMQMessage>(_messages);
@@ -167,34 +185,101 @@ public class ConcurrentSelectorDeliveryManager implements DeliveryManager
}
}
- public synchronized void removeAMessageFromTop() throws AMQException
+ public boolean performGet(AMQProtocolSession protocolSession, AMQChannel channel, boolean acks) throws AMQException
+ {
+ AMQMessage msg = getNextMessage();
+ if(msg == null)
+ {
+ return false;
+ }
+ else
+ {
+
+ try
+ {
+ // if we do not need to wait for client acknowledgements
+ // we can decrement the reference count immediately.
+
+ // By doing this _before_ the send we ensure that it
+ // doesn't get sent if it can't be dequeued, preventing
+ // duplicate delivery on recovery.
+
+ // The send may of course still fail, in which case, as
+ // the message is unacked, it will be lost.
+ if (!acks)
+ {
+ if (_log.isDebugEnabled())
+ {
+ _log.debug("No ack mode so dequeuing message immediately: " + msg.getMessageId());
+ }
+ _queue.dequeue(channel.getStoreContext(), msg);
+ }
+ synchronized(channel)
+ {
+ long deliveryTag = channel.getNextDeliveryTag();
+
+ if (acks)
+ {
+ channel.addUnacknowledgedMessage(msg, deliveryTag, null, _queue);
+ }
+
+ msg.writeGetOk(protocolSession, channel.getChannelId(), deliveryTag, _queue.getMessageCount());
+ _totalMessageSize.addAndGet(-msg.getSize());
+ }
+ }
+ finally
+ {
+ msg.setDeliveredToConsumer();
+ }
+ return true;
+
+ }
+ }
+
+
+ public synchronized void removeAMessageFromTop(StoreContext storeContext) throws AMQException
{
AMQMessage msg = poll();
if (msg != null)
{
- msg.dequeue(_queue);
- }
+ msg.dequeue(storeContext, _queue);
+ _totalMessageSize.getAndAdd(-msg.getSize());
+ }
}
- public synchronized long clearAllMessages() throws AMQException
+// public synchronized long clearAllMessages() throws AMQException
+ public synchronized long clearAllMessages(StoreContext storeContext) throws AMQException
{
long count = 0;
AMQMessage msg = poll();
while (msg != null)
{
- msg.dequeue(_queue);
+ msg.dequeue(storeContext, _queue);
+ count++;
+ _totalMessageSize.set(0L);
count++;
msg = poll();
+
}
return count;
}
+ public synchronized AMQMessage getNextMessage() throws AMQException
+ {
+ return getNextMessage(_messages);
+ }
+
+
+ private AMQMessage getNextMessage(Queue<AMQMessage> messages)
+ {
+ return getNextMessage(messages, false);
+ }
- private AMQMessage getNextMessage(Queue<AMQMessage> messages, Subscription sub)
+ private AMQMessage getNextMessage(Queue<AMQMessage> messages, boolean browsing)
{
AMQMessage message = messages.peek();
- while (message != null && (sub.isBrowser() || message.taken()))
+ while (message != null && (browsing || message.taken()))
{
//remove the already taken message
messages.poll();
@@ -209,7 +294,7 @@ public class ConcurrentSelectorDeliveryManager implements DeliveryManager
AMQMessage message = null;
try
{
- message = getNextMessage(messageQueue, sub);
+ message = getNextMessage(messageQueue, sub.isBrowser());
// message will be null if we have no messages in the messageQueue.
if (message == null)
@@ -225,8 +310,9 @@ public class ConcurrentSelectorDeliveryManager implements DeliveryManager
//remove sent message from our queue.
messageQueue.poll();
+ _totalMessageSize.addAndGet(-message.getSize());
}
- catch (FailedDequeueException e)
+ catch (AMQException e)
{
message.release();
_log.error("Unable to deliver message as dequeue failed: " + e, e);
@@ -282,12 +368,13 @@ public class ConcurrentSelectorDeliveryManager implements DeliveryManager
return _messages.poll();
}
- public void deliver(String name, AMQMessage msg) throws FailedDequeueException
+ public void deliver(StoreContext context, AMQShortString name, AMQMessage msg) throws AMQException
{
if (_log.isDebugEnabled())
{
- _log.debug(id() + "deliver :" + System.identityHashCode(msg));
+ _log.debug(id() + "deliver :" + msg);
}
+ msg.release();
//Check if we have someone to deliver the message to.
_lock.lock();
@@ -299,7 +386,7 @@ public class ConcurrentSelectorDeliveryManager implements DeliveryManager
{
if (_log.isDebugEnabled())
{
- _log.debug(id() + "Testing Message(" + System.identityHashCode(msg) + ") for Queued Delivery");
+ _log.debug(id() + "Testing Message(" + msg + ") for Queued Delivery");
}
if (!msg.isImmediate())
{
@@ -311,7 +398,7 @@ public class ConcurrentSelectorDeliveryManager implements DeliveryManager
//Pre Deliver to all subscriptions
if (_log.isDebugEnabled())
{
- _log.debug(id() + "We have " + _subscriptions.getSubscriptions().size() +
+ _log.debug(id() + "We have " + _subscriptions.getSubscriptions().size() +
" subscribers to give the message to.");
}
for (Subscription sub : _subscriptions.getSubscriptions())
@@ -333,7 +420,7 @@ public class ConcurrentSelectorDeliveryManager implements DeliveryManager
{
if (_log.isDebugEnabled())
{
- _log.debug(id() + "Queuing message(" + System.identityHashCode(msg) +
+ _log.debug(id() + "Queuing message(" + System.identityHashCode(msg) +
") for PreDelivery for subscriber(" + System.identityHashCode(sub) + ")");
}
sub.enqueueForPreDelivery(msg);
@@ -348,7 +435,7 @@ public class ConcurrentSelectorDeliveryManager implements DeliveryManager
if (_log.isDebugEnabled())
{
- _log.debug(id() + "Delivering Message:" + System.identityHashCode(msg) + " to(" +
+ _log.debug(id() + "Delivering Message:" + System.identityHashCode(msg) + " to(" +
System.identityHashCode(s) + ") :" + s);
}
//Deliver the message
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/DefaultQueueRegistry.java b/java/broker/src/main/java/org/apache/qpid/server/queue/DefaultQueueRegistry.java
index 3b73072e30..084612ca41 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/DefaultQueueRegistry.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/queue/DefaultQueueRegistry.java
@@ -21,16 +21,26 @@
package org.apache.qpid.server.queue;
import org.apache.qpid.AMQException;
+import org.apache.qpid.server.virtualhost.VirtualHost;
+import org.apache.qpid.framing.AMQShortString;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentHashMap;
public class DefaultQueueRegistry implements QueueRegistry
{
- private ConcurrentMap<String, AMQQueue> _queueMap = new ConcurrentHashMap<String, AMQQueue>();
+ private ConcurrentMap<AMQShortString, AMQQueue> _queueMap = new ConcurrentHashMap<AMQShortString, AMQQueue>();
- public DefaultQueueRegistry()
+ private final VirtualHost _virtualHost;
+
+ public DefaultQueueRegistry(VirtualHost virtualHost)
+ {
+ _virtualHost = virtualHost;
+ }
+
+ public VirtualHost getVirtualHost()
{
+ return _virtualHost;
}
public void registerQueue(AMQQueue queue) throws AMQException
@@ -38,12 +48,12 @@ public class DefaultQueueRegistry implements QueueRegistry
_queueMap.put(queue.getName(), queue);
}
- public void unregisterQueue(String name) throws AMQException
+ public void unregisterQueue(AMQShortString name) throws AMQException
{
_queueMap.remove(name);
}
- public AMQQueue getQueue(String name)
+ public AMQQueue getQueue(AMQShortString name)
{
return _queueMap.get(name);
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/DeliveryManager.java b/java/broker/src/main/java/org/apache/qpid/server/queue/DeliveryManager.java
index 936afcde10..c7c1643fb8 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/DeliveryManager.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/queue/DeliveryManager.java
@@ -7,9 +7,9 @@
* 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
@@ -21,6 +21,10 @@
package org.apache.qpid.server.queue;
import org.apache.qpid.AMQException;
+import org.apache.qpid.framing.AMQShortString;
+import org.apache.qpid.server.store.StoreContext;
+import org.apache.qpid.server.AMQChannel;
+import org.apache.qpid.server.protocol.AMQProtocolSession;
import java.util.concurrent.Executor;
import java.util.List;
@@ -66,13 +70,18 @@ interface DeliveryManager
* @param msg the message to deliver
* @throws org.apache.qpid.server.queue.FailedDequeueException if the message could not be dequeued
*/
- void deliver(String name, AMQMessage msg) throws FailedDequeueException;
+ void deliver(StoreContext storeContext, AMQShortString name, AMQMessage msg) throws FailedDequeueException, AMQException;
- void removeAMessageFromTop() throws AMQException;
+ void removeAMessageFromTop(StoreContext storeContext) throws AMQException;
- long clearAllMessages() throws AMQException;
+// long clearAllMessages() throws AMQException;
+ long clearAllMessages(StoreContext storeContext) throws AMQException;
List<AMQMessage> getMessages();
void populatePreDeliveryQueue(Subscription subscription);
+
+ boolean performGet(AMQProtocolSession session, AMQChannel channel, boolean acks) throws AMQException;
+
+ long getTotalMessageSize();
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/ExchangeBindings.java b/java/broker/src/main/java/org/apache/qpid/server/queue/ExchangeBindings.java
index 57ca5f0f6e..656549e025 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/ExchangeBindings.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/queue/ExchangeBindings.java
@@ -22,6 +22,7 @@ package org.apache.qpid.server.queue;
import org.apache.qpid.server.exchange.Exchange;
import org.apache.qpid.AMQException;
+import org.apache.qpid.framing.AMQShortString;
import java.util.List;
import java.util.HashSet;
@@ -37,9 +38,9 @@ class ExchangeBindings
static class ExchangeBinding
{
private final Exchange exchange;
- private final String routingKey;
+ private final AMQShortString routingKey;
- ExchangeBinding(String routingKey, Exchange exchange)
+ ExchangeBinding(AMQShortString routingKey, Exchange exchange)
{
this.routingKey = routingKey;
this.exchange = exchange;
@@ -55,7 +56,7 @@ class ExchangeBindings
return exchange;
}
- public String getRoutingKey()
+ public AMQShortString getRoutingKey()
{
return routingKey;
}
@@ -87,7 +88,7 @@ class ExchangeBindings
* are being tracked by the instance has been bound to the exchange
* @param exchange the exchange bound to
*/
- void addBinding(String routingKey, Exchange exchange)
+ void addBinding(AMQShortString routingKey, Exchange exchange)
{
_bindings.add(new ExchangeBinding(routingKey, exchange));
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/InMemoryMessageHandle.java b/java/broker/src/main/java/org/apache/qpid/server/queue/InMemoryMessageHandle.java
new file mode 100644
index 0000000000..740c54370a
--- /dev/null
+++ b/java/broker/src/main/java/org/apache/qpid/server/queue/InMemoryMessageHandle.java
@@ -0,0 +1,127 @@
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+package org.apache.qpid.server.queue;
+
+import org.apache.qpid.AMQException;
+import org.apache.qpid.framing.Content;
+import org.apache.qpid.framing.MessageTransferBody;
+import org.apache.qpid.server.store.StoreContext;
+
+import java.util.LinkedList;
+import java.util.List;
+
+/**
+ */
+public class InMemoryMessageHandle implements AMQMessageHandle
+{
+
+ private MessageTransferBody _messageTransferBody;
+
+ private List<byte[]> _contentBodies = new LinkedList<byte[]>();
+
+ private boolean _redelivered;
+
+ public InMemoryMessageHandle()
+ {
+ }
+
+ public MessageTransferBody getContentHeaderBody(Long messageId) throws AMQException
+ {
+ return _messageTransferBody;
+ }
+
+ public int getBodyCount(Long messageId)
+ {
+ return _contentBodies.size();
+ }
+
+ public long getBodySize(Long messageId) throws AMQException
+ {
+ Content content = getContentHeaderBody(messageId).getBody();
+ return content.getContent().remaining();
+ }
+
+ public byte[] getContentBody(Long messageId, int index) throws AMQException, IllegalArgumentException
+ {
+ if (index > _contentBodies.size() - 1)
+ {
+ throw new IllegalArgumentException("Index " + index + " out of valid range 0 to " +
+ (_contentBodies.size() - 1));
+ }
+ return _contentBodies.get(index);
+ }
+
+ public void addContentBodyFrame(StoreContext storeContext, Long messageId, byte[] contentBody, boolean isLastContentBody)
+ throws AMQException
+ {
+ _contentBodies.add(contentBody);
+ }
+
+ public MessageTransferBody getPublishBody(Long messageId) throws AMQException
+ {
+ return _messageTransferBody;
+ }
+
+ public boolean isRedelivered()
+ {
+ return _redelivered;
+ }
+
+
+ public void setRedelivered(boolean redelivered)
+ {
+ _redelivered = redelivered;
+ }
+
+ public boolean isPersistent(Long messageId) throws AMQException
+ {
+ //todo remove literal values to a constant file such as AMQConstants in common
+ MessageTransferBody chb = getContentHeaderBody(messageId);
+ return chb.getDeliveryMode() == 2;
+ }
+
+ /**
+ * This is called when all the content has been received.
+ * @param publishBody
+ * @param contentHeaderBody
+ * @throws AMQException
+ */
+ public void setPublishAndContentHeaderBody(StoreContext storeContext, Long messageId, MessageTransferBody messageTransferBody)
+ throws AMQException
+ {
+ _messageTransferBody = messageTransferBody;
+ }
+
+ public void removeMessage(StoreContext storeContext, Long messageId) throws AMQException
+ {
+ // NO OP
+ }
+
+ public void enqueue(StoreContext storeContext, Long messageId, AMQQueue queue) throws AMQException
+ {
+ // NO OP
+ }
+
+ public void dequeue(StoreContext storeContext, Long messageId, AMQQueue queue) throws AMQException
+ {
+ // NO OP
+ }
+}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/ManagedQueue.java b/java/broker/src/main/java/org/apache/qpid/server/queue/ManagedQueue.java
index de5d0f55a7..c36cc6bd7b 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/ManagedQueue.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/queue/ManagedQueue.java
@@ -7,9 +7,9 @@
* 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
@@ -23,11 +23,12 @@ package org.apache.qpid.server.queue;
import org.apache.qpid.server.management.MBeanAttribute;
import org.apache.qpid.server.management.MBeanOperation;
import org.apache.qpid.server.management.MBeanOperationParameter;
+import org.apache.qpid.AMQException;
import javax.management.JMException;
import javax.management.MBeanOperationInfo;
-import javax.management.openmbean.TabularData;
import javax.management.openmbean.CompositeData;
+import javax.management.openmbean.TabularData;
import java.io.IOException;
/**
@@ -70,7 +71,7 @@ public interface ManagedQueue
* @throws IOException
*/
@MBeanAttribute(name="QueueDepth", description="Size of messages(KB) in the queue")
- Long getQueueDepth() throws IOException;
+ Long getQueueDepth() throws IOException, JMException;
/**
* Returns the total number of active subscribers to the queue.
@@ -184,7 +185,7 @@ public interface ManagedQueue
description="Message headers for messages in this queue within given index range. eg. from index 1 - 100")
TabularData viewMessages(@MBeanOperationParameter(name="from index", description="from index")int fromIndex,
@MBeanOperationParameter(name="to index", description="to index")int toIndex)
- throws IOException, JMException;
+ throws IOException, JMException, AMQException;
@MBeanOperation(name="viewMessageContent", description="The message content for given Message Id")
CompositeData viewMessageContent(@MBeanOperationParameter(name="Message Id", description="Message Id")long messageId)
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/MessageCleanupException.java b/java/broker/src/main/java/org/apache/qpid/server/queue/MessageCleanupException.java
index bfe0a0ecf1..1e7e6f03d2 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/MessageCleanupException.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/queue/MessageCleanupException.java
@@ -32,4 +32,8 @@ public class MessageCleanupException extends AMQException
{
super("Failed to cleanup message with id " + messageId, e);
}
+ public MessageCleanupException(String message)
+ {
+ super(message);
+ }
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/MessageHandleFactory.java b/java/broker/src/main/java/org/apache/qpid/server/queue/MessageHandleFactory.java
new file mode 100644
index 0000000000..94ab935115
--- /dev/null
+++ b/java/broker/src/main/java/org/apache/qpid/server/queue/MessageHandleFactory.java
@@ -0,0 +1,46 @@
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+package org.apache.qpid.server.queue;
+
+import org.apache.qpid.server.store.MessageStore;
+
+/**
+ * Constructs a message handle based on the publish body, the content header and the queue to which the message
+ * has been routed.
+ *
+ * @author Robert Greig (robert.j.greig@jpmorgan.com)
+ */
+public class MessageHandleFactory
+{
+
+ public AMQMessageHandle createMessageHandle(Long messageId, MessageStore store, boolean persistent)
+ {
+ // just hardcoded for now
+ if (persistent)
+ {
+ return new WeakReferenceMessageHandle(store);
+ }
+ else
+ {
+ return new InMemoryMessageHandle();
+ }
+ }
+}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/MessageMetaData.java b/java/broker/src/main/java/org/apache/qpid/server/queue/MessageMetaData.java
new file mode 100644
index 0000000000..17eee699f1
--- /dev/null
+++ b/java/broker/src/main/java/org/apache/qpid/server/queue/MessageMetaData.java
@@ -0,0 +1,56 @@
+/*
+ *
+ * Copyright (c) 2006 The Apache Software Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.qpid.server.queue;
+
+import org.apache.qpid.framing.MessageTransferBody;
+
+/**
+ * Encapsulates a publish body and a content header. In the context of the message store these are treated as a
+ * single unit.
+ */
+public class MessageMetaData
+{
+ private MessageTransferBody _messageTransferBody;
+
+ private int _contentChunkCount;
+
+ public MessageMetaData(MessageTransferBody messageTransferBody, int contentChunkCount)
+ {
+ _messageTransferBody = messageTransferBody;
+ _contentChunkCount = contentChunkCount;
+ }
+
+ public int getContentChunkCount()
+ {
+ return _contentChunkCount;
+ }
+
+ public void setContentChunkCount(int contentChunkCount)
+ {
+ _contentChunkCount = contentChunkCount;
+ }
+
+ public MessageTransferBody getMessageTransferBody()
+ {
+ return _messageTransferBody;
+ }
+
+ public void setMessageTransferBody(MessageTransferBody messageTransferBody)
+ {
+ _messageTransferBody = messageTransferBody;
+ }
+}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/NoConsumersException.java b/java/broker/src/main/java/org/apache/qpid/server/queue/NoConsumersException.java
index 09f0b00e90..80846d9201 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/NoConsumersException.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/queue/NoConsumersException.java
@@ -22,8 +22,7 @@ package org.apache.qpid.server.queue;
import org.apache.qpid.server.RequiredDeliveryException;
import org.apache.qpid.protocol.AMQConstant;
-
-import java.util.List;
+import org.apache.qpid.server.RequiredDeliveryException;
/**
* Signals that no consumers exist for a message at a given point in time.
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/QueueRegistry.java b/java/broker/src/main/java/org/apache/qpid/server/queue/QueueRegistry.java
index c83f17b98c..c5f235f1b3 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/QueueRegistry.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/queue/QueueRegistry.java
@@ -21,13 +21,17 @@
package org.apache.qpid.server.queue;
import org.apache.qpid.AMQException;
+import org.apache.qpid.server.virtualhost.VirtualHost;
+import org.apache.qpid.framing.AMQShortString;
public interface QueueRegistry
{
+ VirtualHost getVirtualHost();
+
void registerQueue(AMQQueue queue) throws AMQException;
- void unregisterQueue(String name) throws AMQException;
+ void unregisterQueue(AMQShortString name) throws AMQException;
- AMQQueue getQueue(String name);
+ AMQQueue getQueue(AMQShortString name);
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/Subscription.java b/java/broker/src/main/java/org/apache/qpid/server/queue/Subscription.java
index a5672f2b19..5277069d33 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/Subscription.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/queue/Subscription.java
@@ -7,9 +7,9 @@
* 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
@@ -26,11 +26,11 @@ import java.util.Queue;
public interface Subscription
{
- void send(AMQMessage msg, AMQQueue queue) throws FailedDequeueException;
+ void send(AMQMessage msg, AMQQueue queue) throws AMQException;
boolean isSuspended();
- void queueDeleted(AMQQueue queue);
+ void queueDeleted(AMQQueue queue) throws AMQException;
boolean hasFilters();
@@ -44,5 +44,7 @@ public interface Subscription
void close();
- boolean isBrowser();
+ boolean isBrowser();
+
+ boolean wouldSuspend(AMQMessage msg);
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/SubscriptionFactory.java b/java/broker/src/main/java/org/apache/qpid/server/queue/SubscriptionFactory.java
index 2bb77dc649..6cc55f2818 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/SubscriptionFactory.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/queue/SubscriptionFactory.java
@@ -23,6 +23,7 @@ package org.apache.qpid.server.queue;
import org.apache.qpid.server.protocol.AMQProtocolSession;
import org.apache.qpid.AMQException;
import org.apache.qpid.framing.FieldTable;
+import org.apache.qpid.framing.AMQShortString;
/**
* Allows the customisation of the creation of a subscription. This is typically done within an AMQQueue. This
@@ -33,10 +34,10 @@ import org.apache.qpid.framing.FieldTable;
*/
public interface SubscriptionFactory
{
- Subscription createSubscription(int channel, AMQProtocolSession protocolSession, String consumerTag, boolean acks,
+ Subscription createSubscription(int channel, AMQProtocolSession protocolSession, AMQShortString consumerTag, boolean acks,
FieldTable filters, boolean noLocal) throws AMQException;
- Subscription createSubscription(int channel, AMQProtocolSession protocolSession, String consumerTag)
+ Subscription createSubscription(int channel, AMQProtocolSession protocolSession, AMQShortString consumerTag)
throws AMQException;
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/SubscriptionImpl.java b/java/broker/src/main/java/org/apache/qpid/server/queue/SubscriptionImpl.java
index 0a4397cefc..07d74201ef 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/SubscriptionImpl.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/queue/SubscriptionImpl.java
@@ -7,9 +7,9 @@
* 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
@@ -27,6 +27,7 @@ import org.apache.qpid.common.AMQPFilterTypes;
import org.apache.qpid.common.ClientProperties;
import org.apache.qpid.framing.AMQDataBlock;
import org.apache.qpid.framing.AMQFrame;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.framing.Content;
import org.apache.qpid.framing.FieldTable;
import org.apache.qpid.framing.MessageOkBody;
@@ -38,6 +39,8 @@ import org.apache.qpid.server.filter.FilterManager;
import org.apache.qpid.server.filter.FilterManagerFactory;
import org.apache.qpid.server.protocol.AMQProtocolSession;
import org.apache.qpid.util.ConcurrentLinkedQueueAtomicSize;
+import org.apache.qpid.server.store.StoreContext;
+import org.apache.qpid.util.ConcurrentLinkedQueueAtomicSize;
import java.util.Queue;
@@ -56,7 +59,7 @@ public class SubscriptionImpl implements Subscription
public final AMQProtocolSession protocolSession;
- public final String consumerTag;
+ public final AMQShortString consumerTag;
private final Object sessionKey;
@@ -76,12 +79,12 @@ public class SubscriptionImpl implements Subscription
public static class Factory implements SubscriptionFactory
{
- public Subscription createSubscription(int channel, AMQProtocolSession protocolSession, String consumerTag, boolean acks, FieldTable filters, boolean noLocal) throws AMQException
+ public Subscription createSubscription(int channel, AMQProtocolSession protocolSession, AMQShortString consumerTag, boolean acks, FieldTable filters, boolean noLocal) throws AMQException
{
return new SubscriptionImpl(channel, protocolSession, consumerTag, acks, filters, noLocal);
}
- public SubscriptionImpl createSubscription(int channel, AMQProtocolSession protocolSession, String consumerTag)
+ public SubscriptionImpl createSubscription(int channel, AMQProtocolSession protocolSession, AMQShortString consumerTag)
throws AMQException
{
return new SubscriptionImpl(channel, protocolSession, consumerTag, false, null, false);
@@ -89,14 +92,14 @@ public class SubscriptionImpl implements Subscription
}
public SubscriptionImpl(int channelId, AMQProtocolSession protocolSession,
- String consumerTag, boolean acks)
+ AMQShortString consumerTag, boolean acks)
throws AMQException
{
this(channelId, protocolSession, consumerTag, acks, null, false);
}
public SubscriptionImpl(int channelId, AMQProtocolSession protocolSession,
- String consumerTag, boolean acks, FieldTable filters, boolean noLocal)
+ AMQShortString consumerTag, boolean acks, FieldTable filters, boolean noLocal)
throws AMQException
{
AMQChannel channel = protocolSession.getChannel(channelId);
@@ -166,7 +169,7 @@ public class SubscriptionImpl implements Subscription
public SubscriptionImpl(int channel, AMQProtocolSession protocolSession,
- String consumerTag)
+ AMQShortString consumerTag)
throws AMQException
{
this(channel, protocolSession, consumerTag, false);
@@ -205,42 +208,67 @@ public class SubscriptionImpl implements Subscription
* @param queue
* @throws AMQException
*/
- public void send(AMQMessage msg, AMQQueue queue) throws FailedDequeueException
+ public void send(AMQMessage msg, AMQQueue queue) throws AMQException
{
if (msg != null)
{
- try {
- if (!_isBrowser && !_acks) {
- queue.dequeue(msg);
- }
-
- synchronized(channel) {
- long deliveryTag = channel.getNextDeliveryTag();
-
- if (_acks) {
- if (_isBrowser) {
- channel.addUnacknowledgedBrowsedMessage(msg, deliveryTag, consumerTag, queue);
- } else {
- channel.addUnacknowledgedMessage(msg, deliveryTag, consumerTag, queue);
- }
- }
-
- channel.deliver(msg, consumerTag, deliveryTag);
- }
- } finally {
- if (!_isBrowser) {
- msg.setDeliveredToConsumer();
- }
+ if (_isBrowser)
+ {
+ sendToBrowser(msg, queue);
+ }
+ else
+ {
+ sendToConsumer(channel.getStoreContext(), msg, queue);
}
}
else
{
_logger.error("Attempt to send Null message", new NullPointerException());
}
+// if (msg != null)
+// {
+// try
+// {
+// if (!_isBrowser && !_acks)
+// {
+// queue.dequeue(channel.getStoreContext(), msg);
+// }
+//
+// synchronized(channel)
+// {
+// long deliveryTag = channel.getNextDeliveryTag();
+//
+// if (_acks)
+// {
+// if (_isBrowser)
+// {
+// channel.addUnacknowledgedBrowsedMessage(msg, deliveryTag, consumerTag, queue);
+// }
+// else
+// {
+// channel.addUnacknowledgedMessage(msg, deliveryTag, consumerTag, queue);
+// }
+// }
+// msg.enqueue(queue);
+// // channel.deliver(msg, consumerTag, deliveryTag);
+// }
+// }
+// finally
+// {
+// if (!_isBrowser)
+// {
+// msg.setDeliveredToConsumer();
+// }
+// }
+// }
+// else
+// {
+// _logger.error("Attempt to send Null message", new NullPointerException());
+// }
}
// XXX
- /* private void sendToBrowser(AMQMessage msg, AMQQueue queue) throws FailedDequeueException
+ private void sendToBrowser(AMQMessage msg, AMQQueue queue) throws AMQException
{
// We don't decrement the reference here as we don't want to consume the message
// but we do want to send it to the client.
@@ -255,14 +283,13 @@ public class SubscriptionImpl implements Subscription
{
channel.addUnacknowledgedBrowsedMessage(msg, deliveryTag, consumerTag, queue);
}
- ByteBuffer deliver = null;
- if (true) throw new Error("XXX");
- //createEncodedDeliverFrame(deliveryTag, msg.getRoutingKey(), msg.getExchangeName());
- channel.deliver(msg, consumerTag, null);
+// msg.writeDeliver(protocolSession, channel.getChannelId(), deliveryTag, consumerTag);
+ channel.deliver(msg, consumerTag, deliveryTag);
}
}
- private void sendToConsumer(AMQMessage msg, AMQQueue queue) throws FailedDequeueException
+ private void sendToConsumer(StoreContext storeContext, AMQMessage msg, AMQQueue queue)
+ throws AMQException
{
try
{
@@ -277,7 +304,11 @@ public class SubscriptionImpl implements Subscription
// the message is unacked, it will be lost.
if (!_acks)
{
- queue.dequeue(msg);
+ if (_logger.isDebugEnabled())
+ {
+ _logger.debug("No ack mode so dequeuing message immediately: " + msg.getMessageId());
+ }
+ queue.dequeue(storeContext, msg);
}
synchronized(channel)
{
@@ -288,25 +319,30 @@ public class SubscriptionImpl implements Subscription
channel.addUnacknowledgedMessage(msg, deliveryTag, consumerTag, queue);
}
- channel.deliver(msg, consumerTag, new AMQMethodListener() {
- public boolean methodReceived(AMQMethodEvent evt) throws AMQException {
- if (_logger.isDebugEnabled()) {
- _logger.debug("Ack received on channel " + evt.getChannelId());
- }
- // XXX: reject?
- // XXX: multiple
- channel.acknowledgeMessage(deliveryTag, false);
- return true;
- }
- public void error(Exception e) {}
- });
+// msg.writeDeliver(protocolSession, channel.getChannelId(), deliveryTag, consumerTag);
+// channel.deliver(msg, consumerTag, new AMQMethodListener()
+// {
+// public boolean methodReceived(AMQMethodEvent evt) throws AMQException
+// {
+// if (_logger.isDebugEnabled())
+// {
+// _logger.debug("Ack received on channel " + evt.getChannelId());
+// }
+// // XXX: reject?
+// // XXX: multiple
+// channel.acknowledgeMessage(deliveryTag, false);
+// return true;
+// }
+// public void error(Exception e) {}
+// });
+ channel.deliver(msg, consumerTag, deliveryTag);
}
}
finally
{
msg.setDeliveredToConsumer();
}
- }*/
+ }
public boolean isSuspended()
{
@@ -318,7 +354,7 @@ public class SubscriptionImpl implements Subscription
*
* @param queue
*/
- public void queueDeleted(AMQQueue queue)
+ public void queueDeleted(AMQQueue queue) throws AMQException
{
channel.queueDeleted(queue);
}
@@ -369,6 +405,8 @@ public class SubscriptionImpl implements Subscription
}
}
+
+
}
if (_logger.isTraceEnabled())
{
@@ -426,7 +464,8 @@ public class SubscriptionImpl implements Subscription
// Be aware of possible changes to parameter order as versions change.
if (true) throw new Error("XXX");
/*protocolSession.writeFrame(BasicCancelOkBody.createAMQFrame(channel.getChannelId(),
- (byte)8, (byte)0, // AMQP version (major, minor)
+ protocolSession.getProtocolMajorVersion(),
+ protocolSession.getProtocolMinorVersion(),
consumerTag // consumerTag
));*/
_closed = true;
@@ -437,4 +476,9 @@ public class SubscriptionImpl implements Subscription
{
return _isBrowser;
}
+
+ public boolean wouldSuspend(AMQMessage msg)
+ {
+ return channel.wouldSuspend(msg);
+ }
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/SubscriptionSet.java b/java/broker/src/main/java/org/apache/qpid/server/queue/SubscriptionSet.java
index 91e720ea54..e7c90fb201 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/SubscriptionSet.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/queue/SubscriptionSet.java
@@ -137,7 +137,7 @@ class SubscriptionSet implements WeightedSubscriptionManager
++_currentSubscriber;
subscriberScanned();
- if (!subscription.isSuspended())
+ if (!(subscription.isSuspended() || subscription.wouldSuspend(msg)))
{
if (subscription.hasInterest(msg))
{
@@ -204,7 +204,7 @@ class SubscriptionSet implements WeightedSubscriptionManager
*
* @param queue
*/
- public void queueDeleted(AMQQueue queue)
+ public void queueDeleted(AMQQueue queue) throws AMQException
{
for (Subscription s : _subscriptions)
{
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/SynchronizedDeliveryManager.java b/java/broker/src/main/java/org/apache/qpid/server/queue/SynchronizedDeliveryManager.java
deleted file mode 100644
index 54cd3013ea..0000000000
--- a/java/broker/src/main/java/org/apache/qpid/server/queue/SynchronizedDeliveryManager.java
+++ /dev/null
@@ -1,265 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.queue;
-
-import org.apache.qpid.AMQException;
-import org.apache.log4j.Logger;
-
-import java.util.LinkedList;
-import java.util.Queue;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.Executor;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-/**
- * Manages delivery of messages on behalf of a queue
- */
-class SynchronizedDeliveryManager implements DeliveryManager
-{
- private static final Logger _log = Logger.getLogger(SynchronizedDeliveryManager.class);
-
- /**
- * Holds any queued messages
- */
- private final Queue<AMQMessage> _messages = new LinkedList<AMQMessage>();
- /**
- * Ensures that only one asynchronous task is running for this manager at
- * any time.
- */
- private final AtomicBoolean _processing = new AtomicBoolean();
- /**
- * The subscriptions on the queue to whom messages are delivered
- */
- private final SubscriptionManager _subscriptions;
-
- /**
- * An indication of the mode we are in. If this is true then messages are
- * being queued up in _messages for asynchronous delivery. If it is false
- * then messages can be delivered directly as they come in.
- */
- private volatile boolean _queueing;
-
- /**
- * A reference to the queue we are delivering messages for. We need this to be able
- * to pass the code that handles acknowledgements a handle on the queue.
- */
- private final AMQQueue _queue;
-
- SynchronizedDeliveryManager(SubscriptionManager subscriptions, AMQQueue queue)
- {
- _subscriptions = subscriptions;
- _queue = queue;
- }
-
- private synchronized boolean enqueue(AMQMessage msg)
- {
- if (msg.isImmediate())
- {
- return false;
- }
- else
- {
- if (_queueing)
- {
- _messages.offer(msg);
- return true;
- }
- else
- {
- return false;
- }
- }
- }
-
- private synchronized void startQueueing(AMQMessage msg)
- {
- _queueing = true;
- enqueue(msg);
- }
-
- /**
- * Determines whether there are queued messages. Sets _queueing to false if
- * there are no queued messages. This needs to be atomic.
- *
- * @return true if there are queued messages
- */
- public synchronized boolean hasQueuedMessages()
- {
- boolean empty = _messages.isEmpty();
- if (empty)
- {
- _queueing = false;
- }
- return !empty;
- }
-
- public synchronized int getQueueMessageCount()
- {
- return _messages.size();
- }
-
- public synchronized List<AMQMessage> getMessages()
- {
- return new ArrayList<AMQMessage>(_messages);
- }
-
- public void populatePreDeliveryQueue(Subscription subscription)
- {
- //no-op . This DM has no PreDeliveryQueues
- }
-
- public synchronized void removeAMessageFromTop() throws AMQException
- {
- AMQMessage msg = poll();
- if (msg != null)
- {
- msg.dequeue(_queue);
- }
- }
-
- public synchronized long clearAllMessages() throws AMQException
- {
- AMQMessage msg = poll();
- while (msg != null)
- {
- msg.dequeue(_queue);
- msg = poll();
- }
- return 0;
- }
-
- /**
- * Only one thread should ever execute this method concurrently, but
- * it can do so while other threads invoke deliver().
- */
- private void processQueue()
- {
- try
- {
- boolean hasSubscribers = _subscriptions.hasActiveSubscribers();
- while (hasQueuedMessages() && hasSubscribers)
- {
- Subscription next = _subscriptions.nextSubscriber(peek());
- //We don't synchronize access to subscribers so need to re-check
- if (next != null)
- {
- try
- {
- next.send(poll(), _queue);
- }
- catch (AMQException e)
- {
- _log.error("Unable to deliver message: " + e, e);
- }
- }
- else
- {
- hasSubscribers = false;
- }
- }
- }
- finally
- {
- _processing.set(false);
- }
- }
-
- private synchronized AMQMessage peek()
- {
- return _messages.peek();
- }
-
- private synchronized AMQMessage poll()
- {
- return _messages.poll();
- }
-
- /**
- * Requests that the delivery manager start processing the queue asynchronously
- * if there is work that can be done (i.e. there are messages queued up and
- * subscribers that can receive them.
- * <p/>
- * This should be called when subscribers are added, but only after the consume-ok
- * message has been returned as message delivery may start immediately. It should also
- * be called after unsuspending a client.
- * <p/>
- *
- * @param executor the executor on which the delivery should take place
- */
- public void processAsync(Executor executor)
- {
- if (hasQueuedMessages() && _subscriptions.hasActiveSubscribers())
- {
- //are we already running? if so, don't re-run
- if (_processing.compareAndSet(false, true))
- {
- // Do we need this?
- // This executor is created via Executors in AsyncDeliveryConfig which only returns a TPE so cast is ok.
- //if (executor != null && !((ThreadPoolExecutor) executor).isShutdown())
- {
- executor.execute(new Runner());
- }
- }
- }
- }
-
- /**
- * Handles message delivery. The delivery manager is always in one of two modes;
- * it is either queueing messages for asynchronous delivery or delivering
- * directly.
- *
- * @param name the name of the entity on whose behalf we are delivering the message
- * @param msg the message to deliver
- * @throws NoConsumersException if there are no active subscribers to deliver
- * the message to
- */
- public void deliver(String name, AMQMessage msg) throws FailedDequeueException
- {
- // first check whether we are queueing, and enqueue if we are
- if (!enqueue(msg))
- {
- synchronized(this)
- {
- // not queueing so deliver message to 'next' subscriber
- Subscription s = _subscriptions.nextSubscriber(msg);
- if (s == null)
- {
- // no subscribers yet so enter 'queueing' mode and queue this message
- startQueueing(msg);
- }
- else
- {
- s.send(msg, _queue);
- }
- }
- }
-
- }
-
- private class Runner implements Runnable
- {
- public void run()
- {
- processQueue();
- }
- }
-}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/TransientMessageData.java b/java/broker/src/main/java/org/apache/qpid/server/queue/TransientMessageData.java
new file mode 100644
index 0000000000..68f5e9f6c5
--- /dev/null
+++ b/java/broker/src/main/java/org/apache/qpid/server/queue/TransientMessageData.java
@@ -0,0 +1,102 @@
+/*
+ *
+ * Copyright (c) 2006 The Apache Software Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+package org.apache.qpid.server.queue;
+
+import org.apache.qpid.framing.MessageTransferBody;
+import org.apache.qpid.AMQException;
+
+import java.util.List;
+import java.util.LinkedList;
+
+/**
+ * Contains data that is only used in AMQMessage transiently, e.g. while the content
+ * body fragments are arriving.
+ *
+ * Having this data stored in a separate class means that the AMQMessage class avoids
+ * the small overhead of numerous guaranteed-null references.
+ *
+ * @author Apache Software Foundation
+ */
+public class TransientMessageData
+{
+ /**
+ * Stored temporarily until the header has been received at which point it is used when
+ * constructing the handle
+ */
+ private MessageTransferBody _messageTransferBody;
+
+ /**
+ * Keeps a track of how many bytes we have received in body frames
+ */
+ private long _bodyLengthReceived = 0;
+
+ /**
+ * This is stored during routing, to know the queues to which this message should immediately be
+ * delivered. It is <b>cleared after delivery has been attempted</b>. Any persistent record of destinations is done
+ * by the message handle.
+ */
+ private List<AMQQueue> _destinationQueues = new LinkedList<AMQQueue>();
+
+ public MessageTransferBody getMessageTransferBody()
+ {
+ return _messageTransferBody;
+ }
+
+ public void setMessageTransferBody(MessageTransferBody messageTransferBody)
+ {
+ _messageTransferBody = messageTransferBody;
+ }
+
+ public List<AMQQueue> getDestinationQueues()
+ {
+ return _destinationQueues;
+ }
+
+ public void setDestinationQueues(List<AMQQueue> destinationQueues)
+ {
+ _destinationQueues = destinationQueues;
+ }
+
+ public long getBodyLengthReceived()
+ {
+ return _bodyLengthReceived;
+ }
+
+ public void addBodyLength(int value)
+ {
+ _bodyLengthReceived += value;
+ }
+
+ public boolean isAllContentReceived() throws AMQException
+ {
+// return _bodyLengthReceived == _contentHeaderBody.bodySize;
+ // MessageTransfer has no mechanism for knowing the full size of the message up front...
+ throw new Error("XXX");
+ }
+
+ public void addDestinationQueue(AMQQueue queue)
+ {
+ _destinationQueues.add(queue);
+ }
+
+ public boolean isPersistent()
+ {
+ //todo remove literal values to a constant file such as AMQConstants in common
+ return _messageTransferBody.getDeliveryMode() == 2;
+ }
+}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/WeakReferenceMessageHandle.java b/java/broker/src/main/java/org/apache/qpid/server/queue/WeakReferenceMessageHandle.java
new file mode 100644
index 0000000000..57c257e021
--- /dev/null
+++ b/java/broker/src/main/java/org/apache/qpid/server/queue/WeakReferenceMessageHandle.java
@@ -0,0 +1,197 @@
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+package org.apache.qpid.server.queue;
+
+import org.apache.qpid.AMQException;
+import org.apache.qpid.framing.Content;
+import org.apache.qpid.framing.MessageTransferBody;
+import org.apache.qpid.server.store.MessageStore;
+import org.apache.qpid.server.store.StoreContext;
+
+import java.lang.ref.WeakReference;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.LinkedList;
+import java.util.Collections;
+
+/**
+ * @author Robert Greig (robert.j.greig@jpmorgan.com)
+ */
+public class WeakReferenceMessageHandle implements AMQMessageHandle
+{
+ private WeakReference<MessageTransferBody> _messageTransferBody;
+
+ private List<WeakReference<byte[]>> _contentBodies;
+
+ private boolean _redelivered;
+
+ private final MessageStore _messageStore;
+
+
+ public WeakReferenceMessageHandle(MessageStore messageStore)
+ {
+ _messageStore = messageStore;
+ }
+
+ public MessageTransferBody getContentHeaderBody(Long messageId) throws AMQException
+ {
+ MessageTransferBody mtb = (_messageTransferBody != null?_messageTransferBody.get():null);
+ if (mtb == null)
+ {
+ MessageMetaData mmd = _messageStore.getMessageMetaData(messageId);
+ mtb = mmd.getMessageTransferBody();
+ _messageTransferBody = new WeakReference<MessageTransferBody>(mtb);
+ }
+ return mtb;
+ }
+
+ public int getBodyCount(Long messageId) throws AMQException
+ {
+ if (_contentBodies == null)
+ {
+ MessageMetaData mmd = _messageStore.getMessageMetaData(messageId);
+ int chunkCount = mmd.getContentChunkCount();
+ _contentBodies = new ArrayList<WeakReference<byte[]>>(chunkCount);
+ for (int i = 0; i < chunkCount; i++)
+ {
+ _contentBodies.add(new WeakReference<byte[]>(null));
+ }
+ }
+ return _contentBodies.size();
+ }
+
+ public long getBodySize(Long messageId) throws AMQException
+ {
+ Content content = getContentHeaderBody(messageId).getBody();
+ return content.getContent().remaining();
+ }
+
+ public byte[] getContentBody(Long messageId, int index) throws AMQException, IllegalArgumentException
+ {
+ if (index > _contentBodies.size() - 1)
+ {
+ throw new IllegalArgumentException("Index " + index + " out of valid range 0 to " +
+ (_contentBodies.size() - 1));
+ }
+ WeakReference<byte[]> wr = _contentBodies.get(index);
+ byte[] cb = wr.get();
+ if (cb == null)
+ {
+ cb = _messageStore.getContentBodyChunk(messageId, index);
+ _contentBodies.set(index, new WeakReference<byte[]>(cb));
+ }
+ return cb;
+ }
+
+ /**
+ * Content bodies are set <i>before</i> the publish and header frames
+ * @param storeContext
+ * @param messageId
+ * @param contentBody
+ * @param isLastContentBody
+ * @throws AMQException
+ */
+ public void addContentBodyFrame(StoreContext storeContext, Long messageId, byte[] contentBody, boolean isLastContentBody) throws AMQException
+ {
+ if(_contentBodies == null && isLastContentBody)
+ {
+ _contentBodies = Collections.singletonList(new WeakReference<byte[]>(contentBody));
+
+ }
+ else
+ {
+ if (_contentBodies == null)
+ {
+ _contentBodies = new LinkedList<WeakReference<byte[]>>();
+ }
+
+
+ _contentBodies.add(new WeakReference<byte[]>(contentBody));
+ }
+ _messageStore.storeContentBodyChunk(storeContext, messageId, _contentBodies.size() - 1, contentBody, isLastContentBody);
+ }
+
+ public MessageTransferBody getPublishBody(Long messageId) throws AMQException
+ {
+ MessageTransferBody bpb = (_messageTransferBody != null?_messageTransferBody.get():null);
+ if (bpb == null)
+ {
+ MessageMetaData mmd = _messageStore.getMessageMetaData(messageId);
+ bpb = mmd.getMessageTransferBody();
+ _messageTransferBody = new WeakReference<MessageTransferBody>(bpb);
+ }
+ return bpb;
+ }
+
+ public boolean isRedelivered()
+ {
+ return _redelivered;
+ }
+
+ public void setRedelivered(boolean redelivered)
+ {
+ _redelivered = redelivered;
+ }
+
+ public boolean isPersistent(Long messageId) throws AMQException
+ {
+ //todo remove literal values to a constant file such as AMQConstants in common
+ MessageTransferBody chb = getContentHeaderBody(messageId);
+ return chb.getDeliveryMode() == 2;
+ }
+
+ /**
+ * This is called when all the content has been received.
+ * @param publishBody
+ * @param contentHeaderBody
+ * @throws AMQException
+ */
+ public void setPublishAndContentHeaderBody(StoreContext storeContext, Long messageId, MessageTransferBody messageTransferBody)
+ throws AMQException
+ {
+ // if there are no content bodies the list will be null so we must
+ // create en empty list here
+ Content content = messageTransferBody.getBody();
+ _contentBodies = new LinkedList<WeakReference<byte[]>>();
+ if (content.getContent().remaining() > 0)
+ {
+ _contentBodies.add(new WeakReference<byte[]>(content.getContentAsByteArray()));
+ }
+ _messageStore.storeMessageMetaData(storeContext, messageId, new MessageMetaData(messageTransferBody,
+ _contentBodies.size()));
+ _messageTransferBody = new WeakReference<MessageTransferBody>(messageTransferBody);
+ }
+
+ public void removeMessage(StoreContext storeContext, Long messageId) throws AMQException
+ {
+ _messageStore.removeMessage(storeContext, messageId);
+ }
+
+ public void enqueue(StoreContext storeContext, Long messageId, AMQQueue queue) throws AMQException
+ {
+ _messageStore.enqueueMessage(storeContext, queue.getName(), messageId);
+ }
+
+ public void dequeue(StoreContext storeContext, Long messageId, AMQQueue queue) throws AMQException
+ {
+ _messageStore.dequeueMessage(storeContext, queue.getName(), messageId);
+ }
+}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/registry/ApplicationRegistry.java b/java/broker/src/main/java/org/apache/qpid/server/registry/ApplicationRegistry.java
index 48331843e5..0630d4f39f 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/registry/ApplicationRegistry.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/registry/ApplicationRegistry.java
@@ -23,6 +23,7 @@ package org.apache.qpid.server.registry;
import org.apache.commons.configuration.Configuration;
import org.apache.log4j.Logger;
import org.apache.qpid.server.configuration.Configurator;
+import org.apache.qpid.server.virtualhost.VirtualHost;
import java.util.HashMap;
import java.util.Iterator;
@@ -38,7 +39,7 @@ public abstract class ApplicationRegistry implements IApplicationRegistry
{
private static final Logger _logger = Logger.getLogger(ApplicationRegistry.class);
- private static Map _instanceMap = new HashMap();
+ private static Map<Integer, IApplicationRegistry> _instanceMap = new HashMap<Integer, IApplicationRegistry>();
private final Map<Class<?>, Object> _configuredObjects = new HashMap<Class<?>, Object>();
@@ -62,20 +63,13 @@ public abstract class ApplicationRegistry implements IApplicationRegistry
{
synchronized (ApplicationRegistry.class)
{
- Iterator keyIterator = _instanceMap.keySet().iterator();
+ Iterator<IApplicationRegistry> keyIterator = _instanceMap.values().iterator();
while (keyIterator.hasNext())
{
- int key = (Integer) keyIterator.next();
- IApplicationRegistry instance = (IApplicationRegistry) _instanceMap.get(key);
-
- if ((instance != null))
- {
- if (instance.getMessageStore() != null)
- {
- instance.getMessageStore().close();
- }
- }
+ IApplicationRegistry instance = keyIterator.next();
+
+ instance.close();
}
}
}
@@ -118,7 +112,7 @@ public abstract class ApplicationRegistry implements IApplicationRegistry
{
try
{
- ((IApplicationRegistry) _instanceMap.get(instanceID)).getMessageStore().close();
+ _instanceMap.get(instanceID).close();
}
catch (Exception e)
{
@@ -143,7 +137,7 @@ public abstract class ApplicationRegistry implements IApplicationRegistry
public static IApplicationRegistry getInstance(int instanceID)
{
- IApplicationRegistry instance = (IApplicationRegistry) _instanceMap.get(instanceID);
+ IApplicationRegistry instance = _instanceMap.get(instanceID);
if (instance == null)
{
@@ -168,6 +162,14 @@ public abstract class ApplicationRegistry implements IApplicationRegistry
}
}
+ public void close() throws Exception
+ {
+ for(VirtualHost virtualHost : getVirtualHostRegistry().getVirtualHosts())
+ {
+ virtualHost.close();
+ }
+ }
+
public Configuration getConfiguration()
{
return _configuration;
@@ -193,6 +195,8 @@ public abstract class ApplicationRegistry implements IApplicationRegistry
return instance;
}
+
+
public static void setDefaultApplicationRegistry(String clazz)
{
_APPLICATION_REGISTRY = clazz;
diff --git a/java/broker/src/main/java/org/apache/qpid/server/registry/ConfigurationFileApplicationRegistry.java b/java/broker/src/main/java/org/apache/qpid/server/registry/ConfigurationFileApplicationRegistry.java
index 1eb490d6fb..790421b497 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/registry/ConfigurationFileApplicationRegistry.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/registry/ConfigurationFileApplicationRegistry.java
@@ -38,22 +38,26 @@ import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.security.auth.AuthenticationManager;
import org.apache.qpid.server.security.auth.SASLAuthenticationManager;
import org.apache.qpid.server.store.MessageStore;
+import org.apache.qpid.server.virtualhost.VirtualHost;
+import org.apache.qpid.server.virtualhost.VirtualHostRegistry;
+import org.apache.mina.common.ByteBuffer;
import java.io.File;
+import java.util.*;
+import java.util.concurrent.ConcurrentHashMap;
public class ConfigurationFileApplicationRegistry extends ApplicationRegistry
{
- private QueueRegistry _queueRegistry;
-
- private ExchangeRegistry _exchangeRegistry;
-
- private ExchangeFactory _exchangeFactory;
private ManagedObjectRegistry _managedObjectRegistry;
private AuthenticationManager _authenticationManager;
- private MessageStore _messageStore;
+ private VirtualHostRegistry _virtualHostRegistry;
+
+
+ private final Map<String, VirtualHost> _virtualHosts = new ConcurrentHashMap<String, VirtualHost>();
+
public ConfigurationFileApplicationRegistry(File configurationURL) throws ConfigurationException
{
@@ -91,11 +95,19 @@ public class ConfigurationFileApplicationRegistry extends ApplicationRegistry
public void initialise() throws Exception
{
initialiseManagedObjectRegistry();
- _queueRegistry = new DefaultQueueRegistry();
- _exchangeFactory = new DefaultExchangeFactory();
- _exchangeRegistry = new DefaultExchangeRegistry(_exchangeFactory);
+ _virtualHostRegistry = new VirtualHostRegistry();
_authenticationManager = new SASLAuthenticationManager();
- initialiseMessageStore();
+
+ initialiseVirtualHosts();
+ }
+
+ private void initialiseVirtualHosts() throws Exception
+ {
+ for(String name : getVirtualHostNames())
+ {
+
+ _virtualHostRegistry.registerVirtualHost(new VirtualHost(name,getConfiguration().subset("virtualhosts.virtualhost."+name)));
+ }
}
private void initialiseManagedObjectRegistry()
@@ -111,34 +123,10 @@ public class ConfigurationFileApplicationRegistry extends ApplicationRegistry
}
}
- private void initialiseMessageStore() throws Exception
- {
- String messageStoreClass = _configuration.getString("store.class");
- Class clazz = Class.forName(messageStoreClass);
- Object o = clazz.newInstance();
- if (!(o instanceof MessageStore))
- {
- throw new Exception("Message store class must implement " + MessageStore.class + ". Class " + clazz +
- " does not.");
- }
- _messageStore = (MessageStore) o;
- _messageStore.configure(getQueueRegistry(), "store", _configuration);
- }
-
- public QueueRegistry getQueueRegistry()
+ public VirtualHostRegistry getVirtualHostRegistry()
{
- return _queueRegistry;
- }
-
- public ExchangeRegistry getExchangeRegistry()
- {
- return _exchangeRegistry;
- }
-
- public ExchangeFactory getExchangeFactory()
- {
- return _exchangeFactory;
+ return _virtualHostRegistry;
}
public ManagedObjectRegistry getManagedObjectRegistry()
@@ -151,8 +139,8 @@ public class ConfigurationFileApplicationRegistry extends ApplicationRegistry
return _authenticationManager;
}
- public MessageStore getMessageStore()
+ public Collection<String> getVirtualHostNames()
{
- return _messageStore;
- }
+ return getConfiguration().getList("virtualhosts.virtualhost.name");
+ }
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/registry/IApplicationRegistry.java b/java/broker/src/main/java/org/apache/qpid/server/registry/IApplicationRegistry.java
index cd664f9a4b..703aed69d2 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/registry/IApplicationRegistry.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/registry/IApplicationRegistry.java
@@ -26,8 +26,12 @@ import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.management.ManagedObjectRegistry;
import org.apache.qpid.server.security.auth.AuthenticationManager;
import org.apache.qpid.server.store.MessageStore;
+import org.apache.qpid.server.virtualhost.VirtualHost;
+import org.apache.qpid.server.virtualhost.VirtualHostRegistry;
import org.apache.commons.configuration.Configuration;
+import java.util.Collection;
+
public interface IApplicationRegistry
{
/**
@@ -35,7 +39,9 @@ public interface IApplicationRegistry
* that need access to the application registry itself for initialisation are able to use it. Attempting to
* initialise in the constructor will lead to failures since the registry reference will not have been set.
*/
- void initialise() throws Exception;
+ void initialise() throws Exception;
+
+ void close() throws Exception;
/**
* This gets access to a "configured object". A configured object has fields populated from a the configuration
@@ -54,15 +60,11 @@ public interface IApplicationRegistry
*/
Configuration getConfiguration();
- QueueRegistry getQueueRegistry();
-
- ExchangeRegistry getExchangeRegistry();
-
- ExchangeFactory getExchangeFactory();
-
ManagedObjectRegistry getManagedObjectRegistry();
AuthenticationManager getAuthenticationManager();
- MessageStore getMessageStore();
+ Collection<String> getVirtualHostNames();
+
+ VirtualHostRegistry getVirtualHostRegistry();
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/AuthenticationManager.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/AuthenticationManager.java
index 9f4addd7ee..6cee2ee452 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/AuthenticationManager.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/security/auth/AuthenticationManager.java
@@ -20,6 +20,8 @@
*/
package org.apache.qpid.server.security.auth;
+import org.apache.qpid.framing.AMQShortString;
+
import javax.security.sasl.SaslException;
import javax.security.sasl.SaslServer;
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/NullAuthenticationManager.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/NullAuthenticationManager.java
index 14cce86715..5c21dd4de4 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/NullAuthenticationManager.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/security/auth/NullAuthenticationManager.java
@@ -22,6 +22,7 @@ package org.apache.qpid.server.security.auth;
import org.apache.qpid.server.security.auth.AuthenticationManager;
import org.apache.qpid.server.security.auth.AuthenticationResult;
+import org.apache.qpid.framing.AMQShortString;
import javax.security.sasl.SaslException;
import javax.security.sasl.SaslServer;
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/SASLAuthenticationManager.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/SASLAuthenticationManager.java
index 21eb80c69d..e96bd68cad 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/SASLAuthenticationManager.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/security/auth/SASLAuthenticationManager.java
@@ -24,6 +24,7 @@ import org.apache.commons.configuration.Configuration;
import org.apache.log4j.Logger;
import org.apache.qpid.server.registry.ApplicationRegistry;
import org.apache.qpid.configuration.PropertyUtils;
+import org.apache.qpid.framing.AMQShortString;
import javax.security.auth.callback.CallbackHandler;
import javax.security.sasl.Sasl;
diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/amqplain/AmqPlainSaslServer.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/amqplain/AmqPlainSaslServer.java
index c364ca1d8d..a943003bd3 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/amqplain/AmqPlainSaslServer.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/security/auth/amqplain/AmqPlainSaslServer.java
@@ -56,13 +56,13 @@ public class AmqPlainSaslServer implements SaslServer
try
{
final FieldTable ft = FieldTableFactory.newFieldTable(ByteBuffer.wrap(response), response.length);
- String username = (String) ft.get("LOGIN");
+ String username = (String) ft.getString("LOGIN");
// we do not care about the prompt but it throws if null
NameCallback nameCb = new NameCallback("prompt", username);
// we do not care about the prompt but it throws if null
PasswordCallback passwordCb = new PasswordCallback("prompt", false);
// TODO: should not get pwd as a String but as a char array...
- String pwd = (String) ft.get("PASSWORD");
+ String pwd = (String) ft.getString("PASSWORD");
passwordCb.setPassword(pwd.toCharArray());
AuthorizeCallback authzCb = new AuthorizeCallback(username, username);
Callback[] callbacks = new Callback[]{nameCb, passwordCb, authzCb};
diff --git a/java/broker/src/main/java/org/apache/qpid/server/state/AMQStateManager.java b/java/broker/src/main/java/org/apache/qpid/server/state/AMQStateManager.java
index 6f158c89d6..b80ed8b408 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/state/AMQStateManager.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/state/AMQStateManager.java
@@ -21,17 +21,23 @@
package org.apache.qpid.server.state;
import org.apache.qpid.AMQException;
+import org.apache.qpid.AMQConnectionException;
+import org.apache.qpid.protocol.AMQConstant;
import org.apache.qpid.framing.*;
import org.apache.qpid.protocol.AMQMethodEvent;
import org.apache.qpid.server.exchange.ExchangeRegistry;
import org.apache.qpid.server.handler.*;
+import org.apache.qpid.protocol.AMQMethodEvent;
import org.apache.qpid.protocol.AMQMethodListener;
import org.apache.qpid.server.protocol.AMQProtocolSession;
import org.apache.qpid.server.queue.QueueRegistry;
+import org.apache.qpid.server.AMQChannel;
+import org.apache.qpid.server.virtualhost.VirtualHostRegistry;
import org.apache.log4j.Logger;
import java.util.HashMap;
import java.util.Map;
+import java.util.EnumMap;
import java.util.concurrent.CopyOnWriteArraySet;
/**
@@ -44,8 +50,7 @@ public class AMQStateManager implements AMQMethodListener
{
private static final Logger _logger = Logger.getLogger(AMQStateManager.class);
- private final QueueRegistry _queueRegistry;
- private final ExchangeRegistry _exchangeRegistry;
+ private final VirtualHostRegistry _virtualHostRegistry;
private final AMQProtocolSession _protocolSession;
/**
* The current state
@@ -56,20 +61,20 @@ public class AMQStateManager implements AMQMethodListener
* Maps from an AMQState instance to a Map from Class to StateTransitionHandler.
* The class must be a subclass of AMQFrame.
*/
- private final Map<AMQState, Map<Class<? extends AMQMethodBody>, StateAwareMethodListener<? extends AMQMethodBody>>> _state2HandlersMap =
- new HashMap<AMQState, Map<Class<? extends AMQMethodBody>, StateAwareMethodListener<? extends AMQMethodBody>>>();
+ private final EnumMap<AMQState, Map<Class<? extends AMQMethodBody>, StateAwareMethodListener<? extends AMQMethodBody>>> _state2HandlersMap =
+ new EnumMap<AMQState, Map<Class<? extends AMQMethodBody>, StateAwareMethodListener<? extends AMQMethodBody>>>(AMQState.class);
+
private CopyOnWriteArraySet<StateListener> _stateListeners = new CopyOnWriteArraySet<StateListener>();
- public AMQStateManager(QueueRegistry queueRegistry, ExchangeRegistry exchangeRegistry, AMQProtocolSession protocolSession)
+ public AMQStateManager(VirtualHostRegistry virtualHostRegistry, AMQProtocolSession protocolSession)
{
- this(AMQState.CONNECTION_NOT_STARTED, true, queueRegistry, exchangeRegistry, protocolSession);
+ this(AMQState.CONNECTION_NOT_STARTED, true, virtualHostRegistry, protocolSession);
}
- protected AMQStateManager(AMQState initial, boolean register, QueueRegistry queueRegistry, ExchangeRegistry exchangeRegistry, AMQProtocolSession protocolSession)
+ protected AMQStateManager(AMQState initial, boolean register, VirtualHostRegistry virtualHostRegistry, AMQProtocolSession protocolSession)
{
- _queueRegistry = queueRegistry;
- _exchangeRegistry = exchangeRegistry;
+ _virtualHostRegistry = virtualHostRegistry;
_protocolSession = protocolSession;
_currentState = initial;
if (register)
@@ -80,14 +85,7 @@ public class AMQStateManager implements AMQMethodListener
protected void registerListeners()
{
- Map<Class<? extends AMQMethodBody>, StateAwareMethodListener<? extends AMQMethodBody>> frame2handlerMap =
- new HashMap<Class<? extends AMQMethodBody>, StateAwareMethodListener<? extends AMQMethodBody>>();
-
- // we need to register a map for the null (i.e. all state) handlers otherwise you get
- // a stack overflow in the handler searching code when you present it with a frame for which
- // no handlers are registered
- //
- _state2HandlersMap.put(null, frame2handlerMap);
+ Map<Class<? extends AMQMethodBody>, StateAwareMethodListener<? extends AMQMethodBody>> frame2handlerMap;
frame2handlerMap = new HashMap<Class<? extends AMQMethodBody>, StateAwareMethodListener<? extends AMQMethodBody>>();
frame2handlerMap.put(ConnectionStartOkBody.class, ConnectionStartOkMethodHandler.getInstance());
@@ -179,12 +177,24 @@ public class AMQStateManager implements AMQMethodListener
StateAwareMethodListener<B> handler = findStateTransitionHandler(_currentState, evt.getMethod());
if (handler != null)
{
- handler.methodReceived(_protocolSession, evt);
+ checkChannel(evt, _protocolSession);
+ handler.methodReceived(this, evt);
return true;
}
return false;
}
+ private <B extends AMQMethodBody> void checkChannel(AMQMethodEvent<B> evt, AMQProtocolSession protocolSession)
+ throws AMQException
+ {
+ if(evt.getChannelId() != 0
+ && !(evt.getMethod() instanceof ChannelOpenBody)
+ && protocolSession.getChannel(evt.getChannelId()) == null)
+ {
+ throw evt.getMethod().getConnectionException(AMQConstant.CHANNEL_ERROR.getCode(),"No such channel: " + evt.getChannelId());
+ }
+ }
+
protected <B extends AMQMethodBody> StateAwareMethodListener<B> findStateTransitionHandler(AMQState currentState,
B frame)
throws IllegalStateTransitionException
@@ -196,26 +206,14 @@ public class AMQStateManager implements AMQMethodListener
final Map<Class<? extends AMQMethodBody>, StateAwareMethodListener<? extends AMQMethodBody>>
classToHandlerMap = _state2HandlersMap.get(currentState);
- if (classToHandlerMap == null)
- {
- // if no specialised per state handler is registered look for a
- // handler registered for "all" states
- return findStateTransitionHandler(null, frame);
- }
- final StateAwareMethodListener<B> handler = (StateAwareMethodListener<B>) classToHandlerMap.get(frame.getClass());
+ final StateAwareMethodListener<B> handler = classToHandlerMap == null
+ ? null
+ : (StateAwareMethodListener<B>) classToHandlerMap.get(frame.getClass());
+
if (handler == null)
{
- if (currentState == null)
- {
- _logger.debug("No state transition handler defined for receiving frame " + frame);
- return null;
- }
- else
- {
- // if no specialised per state handler is registered look for a
- // handler registered for "all" states
- return findStateTransitionHandler(null, frame);
- }
+ _logger.debug("No state transition handler defined for receiving frame " + frame);
+ return null;
}
else
{
@@ -233,4 +231,14 @@ public class AMQStateManager implements AMQMethodListener
{
_stateListeners.remove(listener);
}
+
+ public VirtualHostRegistry getVirtualHostRegistry()
+ {
+ return _virtualHostRegistry;
+ }
+
+ public AMQProtocolSession getProtocolSession()
+ {
+ return _protocolSession;
+ }
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/state/StateAwareMethodListener.java b/java/broker/src/main/java/org/apache/qpid/server/state/StateAwareMethodListener.java
index 23f0691d00..99d5d7fe88 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/state/StateAwareMethodListener.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/state/StateAwareMethodListener.java
@@ -25,6 +25,7 @@ import org.apache.qpid.protocol.AMQMethodEvent;
import org.apache.qpid.server.protocol.AMQProtocolSession;
import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.exchange.ExchangeRegistry;
+import org.apache.qpid.server.virtualhost.VirtualHostRegistry;
import org.apache.qpid.framing.AMQMethodBody;
/**
@@ -34,7 +35,5 @@ import org.apache.qpid.framing.AMQMethodBody;
*/
public interface StateAwareMethodListener <B extends AMQMethodBody>
{
- void methodReceived(AMQProtocolSession protocolSession,
- AMQMethodEvent<B> evt)
- throws AMQException;
+ void methodReceived(AMQStateManager stateManager, AMQMethodEvent<B> evt) throws AMQException;
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/store/MemoryMessageStore.java b/java/broker/src/main/java/org/apache/qpid/server/store/MemoryMessageStore.java
index 328aed81d9..ab887c2263 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/store/MemoryMessageStore.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/store/MemoryMessageStore.java
@@ -7,9 +7,9 @@
* 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
@@ -23,11 +23,14 @@ package org.apache.qpid.server.store;
import org.apache.commons.configuration.Configuration;
import org.apache.log4j.Logger;
import org.apache.qpid.AMQException;
-import org.apache.qpid.server.queue.AMQMessage;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.server.queue.AMQQueue;
-import org.apache.qpid.server.queue.QueueRegistry;
+import org.apache.qpid.server.queue.MessageMetaData;
+import org.apache.qpid.server.virtualhost.VirtualHost;
+import java.util.ArrayList;
import java.util.List;
+import java.util.Collections;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicLong;
@@ -43,103 +46,141 @@ public class MemoryMessageStore implements MessageStore
private static final String HASHTABLE_CAPACITY_CONFIG = "hashtable-capacity";
- protected ConcurrentMap<Long, AMQMessage> _messageMap;
+ protected ConcurrentMap<Long, MessageMetaData> _metaDataMap;
+
+ protected ConcurrentMap<Long, List<byte[]>> _contentBodyMap;
private final AtomicLong _messageId = new AtomicLong(1);
public void configure()
{
- _log.info("Using capacity " + DEFAULT_HASHTABLE_CAPACITY + " for hash table");
- _messageMap = new ConcurrentHashMap<Long, AMQMessage>(DEFAULT_HASHTABLE_CAPACITY);
+ _log.info("Using capacity " + DEFAULT_HASHTABLE_CAPACITY + " for hash tables");
+ _metaDataMap = new ConcurrentHashMap<Long, MessageMetaData>(DEFAULT_HASHTABLE_CAPACITY);
+ _contentBodyMap = new ConcurrentHashMap<Long, List<byte[]>>(DEFAULT_HASHTABLE_CAPACITY);
}
public void configure(String base, Configuration config)
{
int hashtableCapacity = config.getInt(base + "." + HASHTABLE_CAPACITY_CONFIG, DEFAULT_HASHTABLE_CAPACITY);
- _log.info("Using capacity " + hashtableCapacity + " for hash table");
- _messageMap = new ConcurrentHashMap<Long, AMQMessage>(hashtableCapacity);
+ _log.info("Using capacity " + hashtableCapacity + " for hash tables");
+ _metaDataMap = new ConcurrentHashMap<Long, MessageMetaData>(hashtableCapacity);
+ _contentBodyMap = new ConcurrentHashMap<Long, List<byte[]>>(hashtableCapacity);
}
- public void configure(QueueRegistry queueRegistry, String base, Configuration config) throws Exception
+ public void configure(VirtualHost virtualHost, String base, Configuration config) throws Exception
{
configure(base, config);
}
public void close() throws Exception
{
- if (_messageMap != null)
+ if (_metaDataMap != null)
{
- _messageMap.clear();
- _messageMap = null;
+ _metaDataMap.clear();
+ _metaDataMap = null;
+ }
+ if (_contentBodyMap != null)
+ {
+ _contentBodyMap.clear();
+ _contentBodyMap = null;
}
}
- public void put(AMQMessage msg)
- {
- _messageMap.put(msg.getMessageId(), msg);
- }
-
- public void removeMessage(long messageId)
+ public void removeMessage(StoreContext context, Long messageId)
{
if (_log.isDebugEnabled())
{
_log.debug("Removing message with id " + messageId);
}
- _messageMap.remove(messageId);
+ _metaDataMap.remove(messageId);
+ _contentBodyMap.remove(messageId);
}
public void createQueue(AMQQueue queue) throws AMQException
{
- //To change body of implemented methods use File | Settings | File Templates.
+ // Not required to do anything
}
- public void removeQueue(String name) throws AMQException
+ public void removeQueue(AMQShortString name) throws AMQException
{
- //To change body of implemented methods use File | Settings | File Templates.
+ // Not required to do anything
}
- public void enqueueMessage(String name, long messageId) throws AMQException
+ public void enqueueMessage(StoreContext context, AMQShortString name, Long messageId) throws AMQException
{
- //To change body of implemented methods use File | Settings | File Templates.
+ // Not required to do anything
}
- public void dequeueMessage(String name, long messageId) throws AMQException
+ public void dequeueMessage(StoreContext context, AMQShortString name, Long messageId) throws AMQException
{
- //To change body of implemented methods use File | Settings | File Templates.
+ // Not required to do anything
}
- public void beginTran() throws AMQException
+ public void beginTran(StoreContext context) throws AMQException
{
- //To change body of implemented methods use File | Settings | File Templates.
+ // Not required to do anything
}
- public void commitTran() throws AMQException
+ public void commitTran(StoreContext context) throws AMQException
{
- //To change body of implemented methods use File | Settings | File Templates.
+ // Not required to do anything
}
- public void abortTran() throws AMQException
+ public void abortTran(StoreContext context) throws AMQException
{
- //To change body of implemented methods use File | Settings | File Templates.
+ // Not required to do anything
}
- public boolean inTran()
+ public boolean inTran(StoreContext context)
{
return false;
}
public List<AMQQueue> createQueues() throws AMQException
{
- return null; //To change body of implemented methods use File | Settings | File Templates.
+ return null;
}
- public long getNewMessageId()
+ public Long getNewMessageId()
{
return _messageId.getAndIncrement();
}
- public AMQMessage getMessage(long messageId)
+ public void storeContentBodyChunk(StoreContext context, Long messageId, int index, byte[] contentBody, boolean lastContentBody)
+ throws AMQException
+ {
+ List<byte[]> bodyList = _contentBodyMap.get(messageId);
+
+ if(bodyList == null && lastContentBody)
+ {
+ _contentBodyMap.put(messageId, Collections.singletonList(contentBody));
+ }
+ else
+ {
+ if (bodyList == null)
+ {
+ bodyList = new ArrayList<byte[]>();
+ _contentBodyMap.put(messageId, bodyList);
+ }
+
+ bodyList.add(index, contentBody);
+ }
+ }
+
+ public void storeMessageMetaData(StoreContext context, Long messageId, MessageMetaData messageMetaData)
+ throws AMQException
+ {
+ _metaDataMap.put(messageId, messageMetaData);
+ }
+
+ public MessageMetaData getMessageMetaData(Long messageId) throws AMQException
+ {
+ return _metaDataMap.get(messageId);
+ }
+
+ public byte[] getContentBodyChunk(Long messageId, int index) throws AMQException
{
- return _messageMap.get(messageId);
+ List<byte[]> bodyList = _contentBodyMap.get(messageId);
+ return bodyList.get(index);
}
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/store/MessageStore.java b/java/broker/src/main/java/org/apache/qpid/server/store/MessageStore.java
index 8ee1d09862..4b2af7bc22 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/store/MessageStore.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/store/MessageStore.java
@@ -7,9 +7,9 @@
* 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
@@ -22,9 +22,11 @@ package org.apache.qpid.server.store;
import org.apache.commons.configuration.Configuration;
import org.apache.qpid.AMQException;
-import org.apache.qpid.server.queue.AMQMessage;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.server.queue.AMQQueue;
+import org.apache.qpid.server.queue.MessageMetaData;
import org.apache.qpid.server.queue.QueueRegistry;
+import org.apache.qpid.server.virtualhost.VirtualHost;
import java.util.List;
@@ -33,38 +35,37 @@ public interface MessageStore
/**
* Called after instantiation in order to configure the message store. A particular implementation can define
* whatever parameters it wants.
- * @param queueRegistry the registry of queues to be used by this store
+ * @param virtualHost the virtual host using by this store
* @param base the base element identifier from which all configuration items are relative. For example, if the base
* element is "store", the all elements used by concrete classes will be "store.foo" etc.
* @param config the apache commons configuration object
+ * @throws Exception if an error occurs that means the store is unable to configure itself
*/
- void configure(QueueRegistry queueRegistry, String base, Configuration config) throws Exception;
+ void configure(VirtualHost virtualHost, String base, Configuration config) throws Exception;
/**
* Called to close and cleanup any resources used by the message store.
- * @throws Exception
+ * @throws Exception if close fails
*/
void close() throws Exception;
- void put(AMQMessage msg) throws AMQException;
-
- void removeMessage(long messageId) throws AMQException;
+ void removeMessage(StoreContext storeContext, Long messageId) throws AMQException;
void createQueue(AMQQueue queue) throws AMQException;
- void removeQueue(String name) throws AMQException;
+ void removeQueue(AMQShortString name) throws AMQException;
- void enqueueMessage(String name, long messageId) throws AMQException;
+ void enqueueMessage(StoreContext context, AMQShortString name, Long messageId) throws AMQException;
- void dequeueMessage(String name, long messageId) throws AMQException;
+ void dequeueMessage(StoreContext context, AMQShortString name, Long messageId) throws AMQException;
- void beginTran() throws AMQException;
+ void beginTran(StoreContext context) throws AMQException;
- void commitTran() throws AMQException;
+ void commitTran(StoreContext context) throws AMQException;
- void abortTran() throws AMQException;
+ void abortTran(StoreContext context) throws AMQException;
- boolean inTran();
+ boolean inTran(StoreContext context);
/**
* Recreate all queues that were persisted, including re-enqueuing of existing messages
@@ -77,7 +78,14 @@ public interface MessageStore
* Return a valid, currently unused message id.
* @return a message id
*/
- long getNewMessageId();
-}
+ Long getNewMessageId();
+ void storeContentBodyChunk(StoreContext context, Long messageId, int index, byte[] contentBody, boolean lastContentBody) throws AMQException;
+ void storeMessageMetaData(StoreContext context, Long messageId, MessageMetaData messageMetaData) throws AMQException;
+
+ MessageMetaData getMessageMetaData(Long messageId) throws AMQException;
+
+ byte[] getContentBodyChunk(Long messageId, int index) throws AMQException;
+
+}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/store/StoreContext.java b/java/broker/src/main/java/org/apache/qpid/server/store/StoreContext.java
new file mode 100644
index 0000000000..55e5067852
--- /dev/null
+++ b/java/broker/src/main/java/org/apache/qpid/server/store/StoreContext.java
@@ -0,0 +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.server.store;
+
+/**
+ * A context that the store can use to associate with a transactional context. For example, it could store
+ * some kind of txn id.
+ *
+ * @author Apache Software Foundation
+ */
+public class StoreContext
+{
+ private Object _payload;
+
+ public Object getPayload()
+ {
+ return _payload;
+ }
+
+ public void setPayload(Object payload)
+ {
+ _payload = payload;
+ }
+}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/txn/CleanupMessageOperation.java b/java/broker/src/main/java/org/apache/qpid/server/txn/CleanupMessageOperation.java
new file mode 100644
index 0000000000..6d5d3c42f3
--- /dev/null
+++ b/java/broker/src/main/java/org/apache/qpid/server/txn/CleanupMessageOperation.java
@@ -0,0 +1,91 @@
+/*
+ *
+ * Copyright (c) 2006 The Apache Software Foundation
+ *
+ * Licensed 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.txn;
+
+import org.apache.log4j.Logger;
+import org.apache.qpid.AMQException;
+import org.apache.qpid.server.queue.AMQMessage;
+import org.apache.qpid.server.queue.NoConsumersException;
+import org.apache.qpid.server.RequiredDeliveryException;
+import org.apache.qpid.server.store.StoreContext;
+
+import java.util.List;
+
+/**
+ * @author Apache Software Foundation
+ */
+public class CleanupMessageOperation implements TxnOp
+{
+ private static final Logger _log = Logger.getLogger(CleanupMessageOperation.class);
+
+ private final AMQMessage _msg;
+
+ private final List<RequiredDeliveryException> _returns;
+
+ public CleanupMessageOperation(AMQMessage msg, List<RequiredDeliveryException> returns)
+ {
+ _msg = msg;
+ _returns = returns;
+ }
+
+ public void prepare(StoreContext context) throws AMQException
+ {
+ }
+
+ public void undoPrepare()
+ {
+ //don't need to do anything here, if the store's txn failed
+ //when processing prepare then the message was not stored
+ //or enqueued on any queues and can be discarded
+ }
+
+ public void commit(StoreContext context)
+ {
+ //The routers reference can now be released. This is done
+ //here to ensure that it happens after the queues that
+ //enqueue it have incremented their counts (which as a
+ //memory only operation is done in the commit phase).
+ try
+ {
+ _msg.decrementReference(context);
+ }
+ catch (AMQException e)
+ {
+ _log.error("On commiting transaction, failed to cleanup unused message: " + e, e);
+ }
+ try
+ {
+ _msg.checkDeliveredToConsumer();
+ }
+ catch (NoConsumersException e)
+ {
+ //TODO: store this for delivery after the commit-ok
+ _returns.add(e);
+ }
+ catch (AMQException e)
+ {
+ _log.error("On commiting transaction, unable to determine whether delivered to a consumer immediately: " +
+ e, e);
+ }
+ }
+
+ public void rollback(StoreContext context)
+ {
+ // NO OP
+ }
+}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/txn/DeliverMessageOperation.java b/java/broker/src/main/java/org/apache/qpid/server/txn/DeliverMessageOperation.java
new file mode 100644
index 0000000000..4dff514ff4
--- /dev/null
+++ b/java/broker/src/main/java/org/apache/qpid/server/txn/DeliverMessageOperation.java
@@ -0,0 +1,74 @@
+/*
+ *
+ * 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.txn;
+
+import org.apache.log4j.Logger;
+import org.apache.qpid.AMQException;
+import org.apache.qpid.server.queue.AMQMessage;
+import org.apache.qpid.server.queue.AMQQueue;
+import org.apache.qpid.server.store.StoreContext;
+
+/**
+ * @author Robert Greig (robert.j.greig@jpmorgan.com)
+ */
+public class DeliverMessageOperation implements TxnOp
+{
+ private static final Logger _logger = Logger.getLogger(DeliverMessageOperation.class);
+
+ private final AMQMessage _msg;
+
+ private final AMQQueue _queue;
+
+ public DeliverMessageOperation(AMQMessage msg, AMQQueue queue)
+ {
+ _msg = msg;
+ _queue = queue;
+ _msg.incrementReference();
+ }
+
+ public void prepare(StoreContext context) throws AMQException
+ {
+ }
+
+ public void undoPrepare()
+ {
+ }
+
+ public void commit(StoreContext context) throws AMQException
+ {
+ //do the memeory part of the record()
+ _msg.incrementReference();
+ //then process the message
+ try
+ {
+ _queue.process(context, _msg);
+ }
+ catch (AMQException e)
+ {
+ //TODO: is there anything else we can do here? I think not...
+ _logger.error("Error during commit of a queue delivery: " + e, e);
+ }
+ }
+
+ public void rollback(StoreContext storeContext)
+ {
+ }
+}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/txn/LocalTransactionalContext.java b/java/broker/src/main/java/org/apache/qpid/server/txn/LocalTransactionalContext.java
new file mode 100644
index 0000000000..d750ee7f72
--- /dev/null
+++ b/java/broker/src/main/java/org/apache/qpid/server/txn/LocalTransactionalContext.java
@@ -0,0 +1,237 @@
+/*
+ *
+ * Copyright (c) 2006 The Apache Software Foundation
+ *
+ * Licensed 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.txn;
+
+import org.apache.log4j.Logger;
+import org.apache.qpid.AMQException;
+import org.apache.qpid.server.RequiredDeliveryException;
+import org.apache.qpid.server.ack.TxAck;
+import org.apache.qpid.server.ack.UnacknowledgedMessageMap;
+import org.apache.qpid.server.protocol.AMQProtocolSession;
+import org.apache.qpid.server.queue.AMQMessage;
+import org.apache.qpid.server.queue.AMQQueue;
+import org.apache.qpid.server.store.MessageStore;
+import org.apache.qpid.server.store.StoreContext;
+
+import java.util.LinkedList;
+import java.util.List;
+
+/**
+ * A transactional context that only supports local transactions.
+ */
+public class LocalTransactionalContext implements TransactionalContext
+{
+ private static final Logger _log = Logger.getLogger(LocalTransactionalContext.class);
+
+ private final TxnBuffer _txnBuffer = new TxnBuffer();
+
+ private final List<DeliveryDetails> _postCommitDeliveryList = new LinkedList<DeliveryDetails>();
+
+ /**
+ * We keep hold of the ack operation so that we can consolidate acks, i.e. multiple acks within a txn are
+ * consolidated into a single operation
+ */
+ private TxAck _ackOp;
+
+ private List<RequiredDeliveryException> _returnMessages;
+
+ private final MessageStore _messageStore;
+
+ private final StoreContext _storeContext;
+
+ private boolean _inTran = false;
+
+ private boolean _messageDelivered = false;
+
+ private static class DeliveryDetails
+ {
+ public AMQMessage message;
+ public AMQQueue queue;
+
+
+ public DeliveryDetails(AMQMessage message, AMQQueue queue)
+ {
+ this.message = message;
+ this.queue = queue;
+ }
+ }
+
+ public LocalTransactionalContext(MessageStore messageStore, StoreContext storeContext,
+ List<RequiredDeliveryException> returnMessages)
+ {
+ _messageStore = messageStore;
+ _storeContext = storeContext;
+ _returnMessages = returnMessages;
+ //_txnBuffer.enlist(new StoreMessageOperation(messageStore));
+ }
+
+
+ public StoreContext getStoreContext()
+ {
+ return _storeContext;
+ }
+
+ public void rollback() throws AMQException
+ {
+ _txnBuffer.rollback(_storeContext);
+ }
+
+ public void deliver(AMQMessage message, AMQQueue queue) throws AMQException
+ {
+ // A publication will result in the enlisting of several
+ // TxnOps. The first is an op that will store the message.
+ // Following that (and ordering is important), an op will
+ // be added for every queue onto which the message is
+ // enqueued. Finally a cleanup op will be added to decrement
+ // the reference associated with the routing.
+ message.incrementReference();
+ _postCommitDeliveryList.add(new DeliveryDetails(message, queue));
+ _messageDelivered = true;
+ /*_txnBuffer.enlist(new DeliverMessageOperation(message, queue));
+ if (_log.isDebugEnabled())
+ {
+ _log.debug("Incrementing ref count on message and enlisting cleanup operation - id " +
+ message.getMessageId());
+ }
+ message.incrementReference();
+ _messageDelivered = true;
+ _txnBuffer.enlist(new CleanupMessageOperation(message, _returnMessages));
+ */
+ }
+
+ private void checkAck(long deliveryTag, UnacknowledgedMessageMap unacknowledgedMessageMap) throws AMQException
+ {
+ if (!unacknowledgedMessageMap.contains(deliveryTag))
+ {
+ throw new AMQException("Ack with delivery tag " + deliveryTag + " not known for channel");
+ }
+ }
+
+ public void acknowledgeMessage(long deliveryTag, long lastDeliveryTag, boolean multiple,
+ UnacknowledgedMessageMap unacknowledgedMessageMap) throws AMQException
+ {
+ //check that the tag exists to give early failure
+ if (!multiple || deliveryTag > 0)
+ {
+ checkAck(deliveryTag, unacknowledgedMessageMap);
+ }
+ //we use a single txn op for all acks and update this op
+ //as new acks come in. If this is the first ack in the txn
+ //we will need to create and enlist the op.
+ if (_ackOp == null)
+ {
+ beginTranIfNecessary();
+ _ackOp = new TxAck(unacknowledgedMessageMap);
+ _txnBuffer.enlist(_ackOp);
+ }
+ // update the op to include this ack request
+ if (multiple && deliveryTag == 0)
+ {
+ // if have signalled to ack all, that refers only
+ // to all at this time
+ _ackOp.update(lastDeliveryTag, multiple);
+ }
+ else
+ {
+ _ackOp.update(deliveryTag, multiple);
+ }
+ }
+
+ public void messageFullyReceived(boolean persistent) throws AMQException
+ {
+ // Not required in this transactional context
+ }
+
+ public void messageProcessed(AMQProtocolSession protocolSession) throws AMQException
+ {
+ // Not required in this transactional context
+ }
+
+ public void beginTranIfNecessary() throws AMQException
+ {
+ if (!_inTran)
+ {
+ if (_log.isDebugEnabled())
+ {
+ _log.debug("Starting transaction on message store");
+ }
+ _messageStore.beginTran(_storeContext);
+ _inTran = true;
+ }
+ }
+
+ public void commit() throws AMQException
+ {
+ if (_log.isDebugEnabled())
+ {
+ _log.debug("Committing transactional context");
+ }
+ if (_ackOp != null)
+ {
+
+ _messageDelivered = true;
+ _ackOp.consolidate();
+ //already enlisted, after commit will reset regardless of outcome
+ _ackOp = null;
+ }
+
+ if (_messageDelivered && _inTran)
+ {
+ _txnBuffer.enlist(new StoreMessageOperation(_messageStore));
+ }
+ try
+ {
+ _txnBuffer.commit(_storeContext);
+ }
+ finally
+ {
+ _messageDelivered = false;
+ _inTran = _messageStore.inTran(_storeContext);
+ }
+
+ try
+ {
+ postCommitDelivery();
+ }
+ catch (AMQException e)
+ {
+ // OK so what do we do now...?
+ _log.error("Failed to deliver messages following txn commit: " + e, e);
+ }
+ }
+
+ private void postCommitDelivery() throws AMQException
+ {
+ if (_log.isDebugEnabled())
+ {
+ _log.debug("Performing post commit delivery");
+ }
+ try
+ {
+ for (DeliveryDetails dd : _postCommitDeliveryList)
+ {
+ dd.queue.process(_storeContext, dd.message);
+ }
+ }
+ finally
+ {
+ _postCommitDeliveryList.clear();
+ }
+
+ }
+}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/txn/NonTransactionalContext.java b/java/broker/src/main/java/org/apache/qpid/server/txn/NonTransactionalContext.java
new file mode 100644
index 0000000000..f3e6c69cc5
--- /dev/null
+++ b/java/broker/src/main/java/org/apache/qpid/server/txn/NonTransactionalContext.java
@@ -0,0 +1,214 @@
+/*
+ *
+ * Copyright (c) 2006 The Apache Software Foundation
+ *
+ * Licensed 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.txn;
+
+import org.apache.log4j.Logger;
+import org.apache.qpid.AMQException;
+import org.apache.qpid.server.AMQChannel;
+import org.apache.qpid.server.RequiredDeliveryException;
+import org.apache.qpid.server.protocol.AMQProtocolSession;
+import org.apache.qpid.server.ack.UnacknowledgedMessage;
+import org.apache.qpid.server.ack.UnacknowledgedMessageMap;
+import org.apache.qpid.server.queue.AMQMessage;
+import org.apache.qpid.server.queue.AMQQueue;
+import org.apache.qpid.server.queue.NoConsumersException;
+import org.apache.qpid.server.store.MessageStore;
+import org.apache.qpid.server.store.StoreContext;
+
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * @author Apache Software Foundation
+ */
+public class NonTransactionalContext implements TransactionalContext
+{
+ private static final Logger _log = Logger.getLogger(NonTransactionalContext.class);
+
+ /**
+ * Channel is useful for logging
+ */
+ private final AMQChannel _channel;
+
+ /**
+ * Where to put undeliverable messages
+ */
+ private final List<RequiredDeliveryException> _returnMessages;
+
+ private Set<Long> _browsedAcks;
+
+ private final MessageStore _messageStore;
+
+ private StoreContext _storeContext;
+
+ /**
+ * Whether we are in a transaction
+ */
+ private boolean _inTran;
+
+ public NonTransactionalContext(MessageStore messageStore, StoreContext storeContext, AMQChannel channel,
+ List<RequiredDeliveryException> returnMessages, Set<Long> browsedAcks)
+ {
+ _channel = channel;
+ _storeContext = storeContext;
+ _returnMessages = returnMessages;
+ _messageStore = messageStore;
+ _browsedAcks = browsedAcks;
+ }
+
+
+ public StoreContext getStoreContext()
+ {
+ return _storeContext;
+ }
+
+ public void beginTranIfNecessary() throws AMQException
+ {
+ if (!_inTran)
+ {
+ _messageStore.beginTran(_storeContext);
+ _inTran = true;
+ }
+ }
+
+ public void commit() throws AMQException
+ {
+ // Does not apply to this context
+ }
+
+ public void rollback() throws AMQException
+ {
+ // Does not apply to this context
+ }
+
+ public void deliver(AMQMessage message, AMQQueue queue) throws AMQException
+ {
+ try
+ {
+ message.incrementReference();
+ queue.process(_storeContext, message);
+ //following check implements the functionality
+ //required by the 'immediate' flag:
+ message.checkDeliveredToConsumer();
+ }
+ catch (NoConsumersException e)
+ {
+ _returnMessages.add(e);
+ }
+ }
+
+ public void acknowledgeMessage(final long deliveryTag, long lastDeliveryTag,
+ boolean multiple, final UnacknowledgedMessageMap unacknowledgedMessageMap)
+ throws AMQException
+ {
+ if (multiple)
+ {
+ if (deliveryTag == 0)
+ {
+
+ //Spec 2.1.6.11 ... If the multiple field is 1, and the delivery tag is zero,
+ // tells the server to acknowledge all outstanding mesages.
+ _log.info("Multiple ack on delivery tag 0. ACKing all messages. Current count:" +
+ unacknowledgedMessageMap.size());
+ unacknowledgedMessageMap.visit(new UnacknowledgedMessageMap.Visitor()
+ {
+ public boolean callback(UnacknowledgedMessage message) throws AMQException
+ {
+ if (!_browsedAcks.contains(deliveryTag))
+ {
+ if (_log.isDebugEnabled())
+ {
+ _log.debug("Discarding message: " + message.message.getMessageId());
+ }
+ message.discard(_storeContext);
+ }
+ else
+ {
+ _browsedAcks.remove(deliveryTag);
+ }
+ return false;
+ }
+
+ public void visitComplete()
+ {
+ unacknowledgedMessageMap.clear();
+ }
+ });
+ }
+ else
+ {
+ if (!unacknowledgedMessageMap.contains(deliveryTag))
+ {
+ throw new AMQException("Multiple ack on delivery tag " + deliveryTag + " not known for channel");
+ }
+
+ LinkedList<UnacknowledgedMessage> acked = new LinkedList<UnacknowledgedMessage>();
+ unacknowledgedMessageMap.drainTo(acked, deliveryTag);
+ for (UnacknowledgedMessage msg : acked)
+ {
+ if (!_browsedAcks.contains(deliveryTag))
+ {
+ if (_log.isDebugEnabled())
+ {
+ _log.debug("Discarding message: " + msg.message.getMessageId());
+ }
+ msg.discard(_storeContext);
+ }
+ else
+ {
+ _browsedAcks.remove(deliveryTag);
+ }
+ }
+ }
+ }
+ else
+ {
+ UnacknowledgedMessage msg;
+ msg = unacknowledgedMessageMap.remove(deliveryTag);
+
+ if (msg == null)
+ {
+ _log.info("Single ack on delivery tag " + deliveryTag + " not known for channel:" +
+ _channel.getChannelId());
+ throw new AMQException("Single ack on delivery tag " + deliveryTag + " not known for channel:" +
+ _channel.getChannelId());
+ }
+ msg.discard(_storeContext);
+ if (_log.isDebugEnabled())
+ {
+ _log.debug("Received non-multiple ack for messaging with delivery tag " + deliveryTag + " msg id " +
+ msg.message.getMessageId());
+ }
+ }
+ }
+
+ public void messageFullyReceived(boolean persistent) throws AMQException
+ {
+ if (persistent)
+ {
+ _messageStore.commitTran(_storeContext);
+ _inTran = false;
+ }
+ }
+
+ public void messageProcessed(AMQProtocolSession protocolSession) throws AMQException
+ {
+ _channel.processReturns(protocolSession);
+ }
+}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/txn/StoreMessageOperation.java b/java/broker/src/main/java/org/apache/qpid/server/txn/StoreMessageOperation.java
new file mode 100644
index 0000000000..0e4d6c2030
--- /dev/null
+++ b/java/broker/src/main/java/org/apache/qpid/server/txn/StoreMessageOperation.java
@@ -0,0 +1,58 @@
+/*
+ *
+ * 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.txn;
+
+import org.apache.qpid.AMQException;
+import org.apache.qpid.server.store.MessageStore;
+import org.apache.qpid.server.store.StoreContext;
+
+/**
+ * A transactional operation to store messages in an underlying persistent store. When this operation
+ * commits it will do everything to ensure that all messages are safely committed to persistent
+ * storage.
+ */
+public class StoreMessageOperation implements TxnOp
+{
+ private final MessageStore _messsageStore;
+
+ public StoreMessageOperation(MessageStore messageStore)
+ {
+ _messsageStore = messageStore;
+ }
+
+ public void prepare(StoreContext context) throws AMQException
+ {
+ }
+
+ public void undoPrepare()
+ {
+ }
+
+ public void commit(StoreContext context) throws AMQException
+ {
+ _messsageStore.commitTran(context);
+ }
+
+ public void rollback(StoreContext context) throws AMQException
+ {
+ _messsageStore.abortTran(context);
+ }
+}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/txn/TransactionalContext.java b/java/broker/src/main/java/org/apache/qpid/server/txn/TransactionalContext.java
new file mode 100644
index 0000000000..e241ed4874
--- /dev/null
+++ b/java/broker/src/main/java/org/apache/qpid/server/txn/TransactionalContext.java
@@ -0,0 +1,51 @@
+/*
+ *
+ * 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.txn;
+
+import org.apache.qpid.AMQException;
+import org.apache.qpid.server.ack.UnacknowledgedMessageMap;
+import org.apache.qpid.server.queue.AMQMessage;
+import org.apache.qpid.server.queue.AMQQueue;
+import org.apache.qpid.server.protocol.AMQProtocolSession;
+import org.apache.qpid.server.store.StoreContext;
+
+/**
+ * @author Robert Greig (robert.j.greig@jpmorgan.com)
+ */
+public interface TransactionalContext
+{
+ void beginTranIfNecessary() throws AMQException;
+
+ void commit() throws AMQException;
+
+ void rollback() throws AMQException;
+
+ void deliver(AMQMessage message, AMQQueue queue) throws AMQException;
+
+ void acknowledgeMessage(long deliveryTag, long lastDeliveryTag, boolean multiple,
+ UnacknowledgedMessageMap unacknowledgedMessageMap) throws AMQException;
+
+ void messageFullyReceived(boolean persistent) throws AMQException;
+
+ void messageProcessed(AMQProtocolSession protocolSession) throws AMQException;
+
+ StoreContext getStoreContext();
+}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/txn/TxnBuffer.java b/java/broker/src/main/java/org/apache/qpid/server/txn/TxnBuffer.java
index 402065d5e1..069caf0ae1 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/txn/TxnBuffer.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/txn/TxnBuffer.java
@@ -7,9 +7,9 @@
* 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
@@ -22,91 +22,63 @@ package org.apache.qpid.server.txn;
import org.apache.log4j.Logger;
import org.apache.qpid.AMQException;
-import org.apache.qpid.server.store.MessageStore;
+import org.apache.qpid.server.store.StoreContext;
import java.util.ArrayList;
import java.util.List;
/**
* Holds a list of TxnOp instance representing transactional
- * operations.
+ * operations.
*/
public class TxnBuffer
{
- private boolean _containsPersistentChanges = false;
- private final MessageStore _store;
private final List<TxnOp> _ops = new ArrayList<TxnOp>();
private static final Logger _log = Logger.getLogger(TxnBuffer.class);
- public TxnBuffer(MessageStore store)
- {
- _store = store;
- }
-
- public void containsPersistentChanges()
+ public TxnBuffer()
{
- _containsPersistentChanges = true;
}
- public void commit() throws AMQException
+ public void commit(StoreContext context) throws AMQException
{
- if (_containsPersistentChanges)
+ if (prepare(context))
{
- _log.debug("Begin Transaction.");
- _store.beginTran();
- if(prepare())
+ for (TxnOp op : _ops)
{
- _log.debug("Transaction Succeeded");
- _store.commitTran();
- for (TxnOp op : _ops)
- {
- op.commit();
- }
+ op.commit(context);
}
- else
- {
- _log.debug("Transaction Failed");
- _store.abortTran();
- }
- }else{
- if(prepare())
- {
- for (TxnOp op : _ops)
- {
- op.commit();
- }
- }
}
_ops.clear();
}
- private boolean prepare()
- {
+ private boolean prepare(StoreContext context)
+ {
for (int i = 0; i < _ops.size(); i++)
{
TxnOp op = _ops.get(i);
try
{
- op.prepare();
+ op.prepare(context);
}
- catch(Exception e)
+ catch (Exception e)
{
//compensate previously prepared ops
for(int j = 0; j < i; j++)
{
_ops.get(j).undoPrepare();
- }
+ }
return false;
}
}
return true;
- }
+ }
- public void rollback() throws AMQException
+ public void rollback(StoreContext context) throws AMQException
{
for (TxnOp op : _ops)
{
- op.rollback();
+ op.rollback(context);
}
_ops.clear();
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/txn/TxnOp.java b/java/broker/src/main/java/org/apache/qpid/server/txn/TxnOp.java
index e863bab73e..919c078cf0 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/txn/TxnOp.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/txn/TxnOp.java
@@ -7,9 +7,9 @@
* 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
@@ -21,6 +21,7 @@
package org.apache.qpid.server.txn;
import org.apache.qpid.AMQException;
+import org.apache.qpid.server.store.StoreContext;
/**
* This provides the abstraction of an individual operation within a
@@ -29,14 +30,14 @@ import org.apache.qpid.AMQException;
public interface TxnOp
{
/**
- * Do the part of the operation that updates persistent state
+ * Do the part of the operation that updates persistent state
*/
- public void prepare() throws AMQException;
+ public void prepare(StoreContext context) throws AMQException;
/**
* Complete the operation started by prepare. Can now update in
* memory state or make netork transfers.
*/
- public void commit();
+ public void commit(StoreContext context) throws AMQException;
/**
* This is not the same as rollback. Unfortunately the use of an
* in memory reference count as a locking mechanism and a test for
@@ -50,5 +51,5 @@ public interface TxnOp
/**
* Rolls back the operation.
*/
- public void rollback();
+ public void rollback(StoreContext context) throws AMQException;
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/util/NullApplicationRegistry.java b/java/broker/src/main/java/org/apache/qpid/server/util/NullApplicationRegistry.java
index 2e77f33363..e9a3a3d048 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/util/NullApplicationRegistry.java
+++ b/java/broker/src/main/java/org/apache/qpid/server/util/NullApplicationRegistry.java
@@ -33,24 +33,23 @@ import org.apache.qpid.server.security.auth.AuthenticationManager;
import org.apache.qpid.server.security.auth.NullAuthenticationManager;
import org.apache.qpid.server.store.MessageStore;
import org.apache.qpid.server.store.MemoryMessageStore;
+import org.apache.qpid.server.virtualhost.VirtualHost;
+import org.apache.qpid.server.virtualhost.VirtualHostRegistry;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.MapConfiguration;
import java.util.HashMap;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Arrays;
public class NullApplicationRegistry extends ApplicationRegistry
{
- private QueueRegistry _queueRegistry;
-
- private ExchangeRegistry _exchangeRegistry;
-
- private ExchangeFactory _exchangeFactory;
-
private ManagedObjectRegistry _managedObjectRegistry;
private AuthenticationManager _authenticationManager;
- private MessageStore _messageStore;
+ private VirtualHostRegistry _virtualHostRegistry;
public NullApplicationRegistry()
@@ -60,15 +59,16 @@ public class NullApplicationRegistry extends ApplicationRegistry
public void initialise() throws Exception
{
+ _configuration.addProperty("store.class","org.apache.qpid.server.store.MemoryMessageStore");
+
_managedObjectRegistry = new NoopManagedObjectRegistry();
- _queueRegistry = new DefaultQueueRegistry();
- _exchangeFactory = new DefaultExchangeFactory();
- _exchangeRegistry = new DefaultExchangeRegistry(_exchangeFactory);
+ _virtualHostRegistry = new VirtualHostRegistry();
+ VirtualHost dummyHost = new VirtualHost("test",getConfiguration());
+ _virtualHostRegistry.registerVirtualHost(dummyHost);
_authenticationManager = new NullAuthenticationManager();
- _messageStore = new MemoryMessageStore();
- ((MemoryMessageStore)_messageStore).configure();
_configuration.addProperty("heartbeat.delay", 10 * 60); // 10 minutes
+
}
public Configuration getConfiguration()
@@ -76,20 +76,6 @@ public class NullApplicationRegistry extends ApplicationRegistry
return _configuration;
}
- public QueueRegistry getQueueRegistry()
- {
- return _queueRegistry;
- }
-
- public ExchangeRegistry getExchangeRegistry()
- {
- return _exchangeRegistry;
- }
-
- public ExchangeFactory getExchangeFactory()
- {
- return _exchangeFactory;
- }
public ManagedObjectRegistry getManagedObjectRegistry()
{
@@ -101,9 +87,15 @@ public class NullApplicationRegistry extends ApplicationRegistry
return _authenticationManager;
}
- public MessageStore getMessageStore()
+ public Collection<String> getVirtualHostNames()
+ {
+ String[] hosts = {"test"};
+ return Arrays.asList( hosts );
+ }
+
+ public VirtualHostRegistry getVirtualHostRegistry()
{
- return _messageStore;
+ return _virtualHostRegistry;
}
}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/ManagedVirtualHost.java b/java/broker/src/main/java/org/apache/qpid/server/virtualhost/ManagedVirtualHost.java
new file mode 100644
index 0000000000..2c888caac1
--- /dev/null
+++ b/java/broker/src/main/java/org/apache/qpid/server/virtualhost/ManagedVirtualHost.java
@@ -0,0 +1,51 @@
+/*
+ *
+ * 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.virtualhost;
+
+import org.apache.qpid.server.management.MBeanAttribute;
+import org.apache.qpid.server.management.MBeanOperation;
+import org.apache.qpid.server.management.MBeanOperationParameter;
+import org.apache.qpid.server.queue.ManagedQueue;
+import org.apache.qpid.server.exchange.ManagedExchange;
+
+import javax.management.openmbean.TabularData;
+import javax.management.JMException;
+import javax.management.MBeanOperationInfo;
+import java.io.IOException;
+
+/**
+ * The management interface exposed to allow management of an Exchange.
+ * @version 0.1
+ */
+public interface ManagedVirtualHost
+{
+ static final String TYPE = "VirtualHost";
+
+ /**
+ * Returns the name of the managed virtualHost.
+ * @return the name of the exchange.
+ * @throws java.io.IOException
+ */
+ @MBeanAttribute(name="Name", description= TYPE + " Name")
+ String getName() throws IOException;
+
+
+}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHost.java b/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHost.java
new file mode 100644
index 0000000000..1ce5146416
--- /dev/null
+++ b/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHost.java
@@ -0,0 +1,211 @@
+/*
+ *
+ * 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.virtualhost;
+
+import org.apache.qpid.server.queue.QueueRegistry;
+import org.apache.qpid.server.queue.DefaultQueueRegistry;
+import org.apache.qpid.server.exchange.*;
+import org.apache.qpid.server.management.*;
+import org.apache.qpid.server.store.MessageStore;
+import org.apache.qpid.server.registry.ApplicationRegistry;
+import org.apache.qpid.server.configuration.Configurator;
+import org.apache.qpid.server.AMQBrokerManagerMBean;
+import org.apache.commons.configuration.Configuration;
+import org.apache.log4j.Logger;
+
+import javax.management.NotCompliantMBeanException;
+
+public class VirtualHost
+{
+ private static final Logger _logger = Logger.getLogger(VirtualHost.class);
+
+
+ private final String _name;
+
+ private QueueRegistry _queueRegistry;
+
+ private ExchangeRegistry _exchangeRegistry;
+
+ private ExchangeFactory _exchangeFactory;
+
+ private MessageStore _messageStore;
+
+ protected VirtualHostMBean _virtualHostMBean;
+
+ private AMQBrokerManagerMBean _brokerMBean;
+
+
+ /**
+ * Abstract MBean class. This has some of the methods implemented from
+ * management intrerface for exchanges. Any implementaion of an
+ * Exchange MBean should extend this class.
+ */
+ public class VirtualHostMBean extends AMQManagedObject implements ManagedVirtualHost
+ {
+ public VirtualHostMBean() throws NotCompliantMBeanException
+ {
+ super(ManagedVirtualHost.class, "VirtualHost");
+ }
+
+
+ public String getObjectInstanceName()
+ {
+ return _name.toString();
+ }
+
+ public String getName()
+ {
+ return _name.toString();
+ }
+
+ public VirtualHost getVirtualHost()
+ {
+ return VirtualHost.this;
+ }
+
+
+ } // End of MBean class
+
+
+ public VirtualHost(String name, MessageStore store) throws Exception
+ {
+ _name = name;
+
+ _virtualHostMBean = new VirtualHostMBean();
+ // This isn't needed to be registered
+ //_virtualHostMBean.register();
+
+ _queueRegistry = new DefaultQueueRegistry(this);
+ _exchangeFactory = new DefaultExchangeFactory(this);
+ _exchangeRegistry = new DefaultExchangeRegistry(_exchangeFactory);
+
+ _messageStore = store;
+
+ _brokerMBean = new AMQBrokerManagerMBean(_virtualHostMBean);
+ _brokerMBean.register();
+
+ }
+ public VirtualHost(String name, Configuration hostConfig) throws Exception
+ {
+ _name = name;
+
+ _virtualHostMBean = new VirtualHostMBean();
+ // This isn't needed to be registered
+ //_virtualHostMBean.register();
+
+ _queueRegistry = new DefaultQueueRegistry(this);
+ _exchangeFactory = new DefaultExchangeFactory(this);
+ _exchangeRegistry = new DefaultExchangeRegistry(_exchangeFactory);
+
+ initialiseMessageStore(hostConfig);
+
+ _brokerMBean = new AMQBrokerManagerMBean(_virtualHostMBean);
+ _brokerMBean.register();
+
+ }
+
+ private void initialiseMessageStore(Configuration config) throws Exception
+ {
+ String messageStoreClass = config.getString("store.class");
+
+ Class clazz = Class.forName(messageStoreClass);
+ Object o = clazz.newInstance();
+
+ if (!(o instanceof MessageStore))
+ {
+ throw new ClassCastException("Message store class must implement " + MessageStore.class + ". Class " + clazz +
+ " does not.");
+ }
+ _messageStore = (MessageStore) o;
+ _messageStore.configure(this, "store", config);
+ }
+
+
+
+
+ public <T> T getConfiguredObject(Class<T> instanceType, Configuration config)
+ {
+ T instance;
+ try
+ {
+ instance = instanceType.newInstance();
+ }
+ catch (Exception e)
+ {
+ _logger.error("Unable to instantiate configuration class " + instanceType + " - ensure it has a public default constructor");
+ throw new IllegalArgumentException("Unable to instantiate configuration class " + instanceType + " - ensure it has a public default constructor");
+ }
+ Configurator.configure(instance);
+
+ return instance;
+ }
+
+
+ public String getName()
+ {
+ return _name;
+ }
+
+ public QueueRegistry getQueueRegistry()
+ {
+ return _queueRegistry;
+ }
+
+ public ExchangeRegistry getExchangeRegistry()
+ {
+ return _exchangeRegistry;
+ }
+
+ public ExchangeFactory getExchangeFactory()
+ {
+ return _exchangeFactory;
+ }
+
+ public ApplicationRegistry getApplicationRegistry()
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public MessageStore getMessageStore()
+ {
+ return _messageStore;
+ }
+
+ public void close() throws Exception
+ {
+ if(_messageStore != null)
+ {
+ _messageStore.close();
+ }
+ }
+
+ public ManagedObject getBrokerMBean()
+ {
+ return _brokerMBean;
+ }
+
+
+
+ public ManagedObject getManagedObject()
+ {
+ return _virtualHostMBean;
+ }
+}
diff --git a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHostRegistry.java b/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHostRegistry.java
new file mode 100644
index 0000000000..25f67c1cf3
--- /dev/null
+++ b/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHostRegistry.java
@@ -0,0 +1,52 @@
+/*
+ *
+ * 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.virtualhost;
+
+import java.util.Map;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.ArrayList;
+import java.util.concurrent.ConcurrentHashMap;
+
+
+public class VirtualHostRegistry
+{
+ private final Map<String, VirtualHost> _registry = new ConcurrentHashMap<String,VirtualHost>();
+
+ public synchronized void registerVirtualHost(VirtualHost host) throws Exception
+ {
+ if(_registry.containsKey(host.getName()))
+ {
+ throw new Exception("Virtual Host with name " + host.getName() + " already registered.");
+ }
+ _registry.put(host.getName(),host);
+ }
+
+ public VirtualHost getVirtualHost(String name)
+ {
+ return _registry.get(name);
+ }
+
+ public Collection<VirtualHost> getVirtualHosts()
+ {
+ return new ArrayList<VirtualHost>(_registry.values());
+ }
+}
diff --git a/java/broker/src/test/java/org/apache/qpid/server/exchange/HeadersBindingTest.java b/java/broker/src/test/java/org/apache/qpid/server/exchange/HeadersBindingTest.java
index 10aa621f89..86ba96bf5d 100644
--- a/java/broker/src/test/java/org/apache/qpid/server/exchange/HeadersBindingTest.java
+++ b/java/broker/src/test/java/org/apache/qpid/server/exchange/HeadersBindingTest.java
@@ -37,157 +37,157 @@ public class HeadersBindingTest extends TestCase
{
bindHeaders.setString("A", "Value of A");
- matchHeaders.put("A", "Value of A");
+ matchHeaders.setString("A", "Value of A");
assertTrue(new HeadersBinding(bindHeaders).matches(matchHeaders));
}
public void testDefault_2()
{
- bindHeaders.put("A", "Value of A");
+ bindHeaders.setString("A", "Value of A");
- matchHeaders.put("A", "Value of A");
- matchHeaders.put("B", "Value of B");
+ matchHeaders.setString("A", "Value of A");
+ matchHeaders.setString("B", "Value of B");
assertTrue(new HeadersBinding(bindHeaders).matches(matchHeaders));
}
public void testDefault_3()
{
- bindHeaders.put("A", "Value of A");
+ bindHeaders.setString("A", "Value of A");
- matchHeaders.put("A", "Altered value of A");
+ matchHeaders.setString("A", "Altered value of A");
assertFalse(new HeadersBinding(bindHeaders).matches(matchHeaders));
}
public void testAll_1()
{
- bindHeaders.put("X-match", "all");
- bindHeaders.put("A", "Value of A");
+ bindHeaders.setString("X-match", "all");
+ bindHeaders.setString("A", "Value of A");
- matchHeaders.put("A", "Value of A");
+ matchHeaders.setString("A", "Value of A");
assertTrue(new HeadersBinding(bindHeaders).matches(matchHeaders));
}
public void testAll_2()
{
- bindHeaders.put("X-match", "all");
- bindHeaders.put("A", "Value of A");
- bindHeaders.put("B", "Value of B");
+ bindHeaders.setString("X-match", "all");
+ bindHeaders.setString("A", "Value of A");
+ bindHeaders.setString("B", "Value of B");
- matchHeaders.put("A", "Value of A");
+ matchHeaders.setString("A", "Value of A");
assertFalse(new HeadersBinding(bindHeaders).matches(matchHeaders));
}
public void testAll_3()
{
- bindHeaders.put("X-match", "all");
- bindHeaders.put("A", "Value of A");
- bindHeaders.put("B", "Value of B");
+ bindHeaders.setString("X-match", "all");
+ bindHeaders.setString("A", "Value of A");
+ bindHeaders.setString("B", "Value of B");
- matchHeaders.put("A", "Value of A");
- matchHeaders.put("B", "Value of B");
+ matchHeaders.setString("A", "Value of A");
+ matchHeaders.setString("B", "Value of B");
assertTrue(new HeadersBinding(bindHeaders).matches(matchHeaders));
}
public void testAll_4()
{
- bindHeaders.put("X-match", "all");
- bindHeaders.put("A", "Value of A");
- bindHeaders.put("B", "Value of B");
+ bindHeaders.setString("X-match", "all");
+ bindHeaders.setString("A", "Value of A");
+ bindHeaders.setString("B", "Value of B");
- matchHeaders.put("A", "Value of A");
- matchHeaders.put("B", "Value of B");
- matchHeaders.put("C", "Value of C");
+ matchHeaders.setString("A", "Value of A");
+ matchHeaders.setString("B", "Value of B");
+ matchHeaders.setString("C", "Value of C");
assertTrue(new HeadersBinding(bindHeaders).matches(matchHeaders));
}
public void testAll_5()
{
- bindHeaders.put("X-match", "all");
- bindHeaders.put("A", "Value of A");
- bindHeaders.put("B", "Value of B");
+ bindHeaders.setString("X-match", "all");
+ bindHeaders.setString("A", "Value of A");
+ bindHeaders.setString("B", "Value of B");
- matchHeaders.put("A", "Value of A");
- matchHeaders.put("B", "Altered value of B");
- matchHeaders.put("C", "Value of C");
+ matchHeaders.setString("A", "Value of A");
+ matchHeaders.setString("B", "Altered value of B");
+ matchHeaders.setString("C", "Value of C");
assertFalse(new HeadersBinding(bindHeaders).matches(matchHeaders));
}
public void testAny_1()
{
- bindHeaders.put("X-match", "any");
- bindHeaders.put("A", "Value of A");
+ bindHeaders.setString("X-match", "any");
+ bindHeaders.setString("A", "Value of A");
- matchHeaders.put("A", "Value of A");
+ matchHeaders.setString("A", "Value of A");
assertTrue(new HeadersBinding(bindHeaders).matches(matchHeaders));
}
public void testAny_2()
{
- bindHeaders.put("X-match", "any");
- bindHeaders.put("A", "Value of A");
- bindHeaders.put("B", "Value of B");
+ bindHeaders.setString("X-match", "any");
+ bindHeaders.setString("A", "Value of A");
+ bindHeaders.setString("B", "Value of B");
- matchHeaders.put("A", "Value of A");
+ matchHeaders.setString("A", "Value of A");
assertTrue(new HeadersBinding(bindHeaders).matches(matchHeaders));
}
public void testAny_3()
{
- bindHeaders.put("X-match", "any");
- bindHeaders.put("A", "Value of A");
- bindHeaders.put("B", "Value of B");
+ bindHeaders.setString("X-match", "any");
+ bindHeaders.setString("A", "Value of A");
+ bindHeaders.setString("B", "Value of B");
- matchHeaders.put("A", "Value of A");
- matchHeaders.put("B", "Value of B");
+ matchHeaders.setString("A", "Value of A");
+ matchHeaders.setString("B", "Value of B");
assertTrue(new HeadersBinding(bindHeaders).matches(matchHeaders));
}
public void testAny_4()
{
- bindHeaders.put("X-match", "any");
- bindHeaders.put("A", "Value of A");
- bindHeaders.put("B", "Value of B");
+ bindHeaders.setString("X-match", "any");
+ bindHeaders.setString("A", "Value of A");
+ bindHeaders.setString("B", "Value of B");
- matchHeaders.put("A", "Value of A");
- matchHeaders.put("B", "Value of B");
- matchHeaders.put("C", "Value of C");
+ matchHeaders.setString("A", "Value of A");
+ matchHeaders.setString("B", "Value of B");
+ matchHeaders.setString("C", "Value of C");
assertTrue(new HeadersBinding(bindHeaders).matches(matchHeaders));
}
public void testAny_5()
{
- bindHeaders.put("X-match", "any");
- bindHeaders.put("A", "Value of A");
- bindHeaders.put("B", "Value of B");
+ bindHeaders.setString("X-match", "any");
+ bindHeaders.setString("A", "Value of A");
+ bindHeaders.setString("B", "Value of B");
- matchHeaders.put("A", "Value of A");
- matchHeaders.put("B", "Altered value of B");
- matchHeaders.put("C", "Value of C");
+ matchHeaders.setString("A", "Value of A");
+ matchHeaders.setString("B", "Altered value of B");
+ matchHeaders.setString("C", "Value of C");
assertTrue(new HeadersBinding(bindHeaders).matches(matchHeaders));
}
public void testAny_6()
{
- bindHeaders.put("X-match", "any");
- bindHeaders.put("A", "Value of A");
- bindHeaders.put("B", "Value of B");
+ bindHeaders.setString("X-match", "any");
+ bindHeaders.setString("A", "Value of A");
+ bindHeaders.setString("B", "Value of B");
- matchHeaders.put("A", "Altered value of A");
- matchHeaders.put("B", "Altered value of B");
- matchHeaders.put("C", "Value of C");
+ matchHeaders.setString("A", "Altered value of A");
+ matchHeaders.setString("B", "Altered value of B");
+ matchHeaders.setString("C", "Value of C");
assertFalse(new HeadersBinding(bindHeaders).matches(matchHeaders));
}
diff --git a/java/broker/test/lib/README b/java/broker/test/lib/README
deleted file mode 100644
index aa57bb004b..0000000000
--- a/java/broker/test/lib/README
+++ /dev/null
@@ -1 +0,0 @@
-Junit copied here momentarily.
diff --git a/java/broker/test/lib/junit/junit-4.0.jar b/java/broker/test/lib/junit/junit-4.0.jar
deleted file mode 100644
index b20406924a..0000000000
--- a/java/broker/test/lib/junit/junit-4.0.jar
+++ /dev/null
Binary files differ
diff --git a/java/broker/test/lib/junit/junit.jar b/java/broker/test/lib/junit/junit.jar
deleted file mode 100644
index 674d71e89e..0000000000
--- a/java/broker/test/lib/junit/junit.jar
+++ /dev/null
Binary files differ
diff --git a/java/client/dist/readme.txt b/java/client/dist/readme.txt
deleted file mode 100644
index b5f7b107b6..0000000000
--- a/java/client/dist/readme.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-This directory is deliberately empty.
-AMQP JAR files will be built here during the build process.
diff --git a/java/client/distribution/pom.xml b/java/client/distribution/pom.xml
new file mode 100644
index 0000000000..dfbe8b83c2
--- /dev/null
+++ b/java/client/distribution/pom.xml
@@ -0,0 +1,155 @@
+<!--
+ 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.
+ -->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>org.apache.qpid</groupId>
+ <artifactId>qpid-client-distribution</artifactId>
+ <packaging>jar</packaging>
+ <version>1.0-incubating-M2-SNAPSHOT</version>
+ <name>Qpid Client Distributions</name>
+ <url>http://cwiki.apache.org/confluence/display/qpid</url>
+
+ <parent>
+ <groupId>org.apache.qpid</groupId>
+ <artifactId>qpid</artifactId>
+ <version>1.0-incubating-M2-SNAPSHOT</version>
+ </parent>
+
+ <properties>
+ <topDirectoryLocation>..</topDirectoryLocation>
+ <java.source.version>1.5</java.source.version>
+ <qpid.version>${pom.version}</qpid.version>
+ <qpid.targetDir>${project.build.directory}</qpid.targetDir>
+ <qpid.root>${basedir}/..</qpid.root>
+ </properties>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.qpid</groupId>
+ <artifactId>qpid-client</artifactId>
+ <type>jar</type>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <pluginManagement>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <configuration>
+ <source>${java.source.version}</source>
+ <target>${java.source.version}</target>
+ </configuration>
+ </plugin>
+
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-assembly-plugin</artifactId>
+ <version>${assembly.version}</version>
+ <configuration>
+ <descriptors>
+ <descriptor>src/main/assembly/client-bin.xml</descriptor>
+ </descriptors>
+ <finalName>qpid-${pom.version}</finalName>
+ <outputDirectory>${qpid.targetDir}</outputDirectory>
+ <tarLongFileMode>gnu</tarLongFileMode>
+ </configuration>
+ </plugin>
+
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-jar-plugin</artifactId>
+ <configuration>
+ <finalName>qpid-incubating</finalName>
+ <archive>
+ <manifest>
+ <addClasspath>true</addClasspath>
+ </manifest>
+ </archive>
+ </configuration>
+ </plugin>
+
+ </plugins>
+ </pluginManagement>
+
+ <plugins>
+ <plugin>
+ <artifactId>maven-assembly-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>distribution-package</id>
+ <phase>package</phase>
+ <goals>
+ <goal>single</goal>
+ </goals>
+ <configuration>
+ <descriptors>
+ <descriptor>src/main/assembly/client-bin.xml</descriptor>
+ <descriptor>src/main/assembly/client-src.xml</descriptor>
+ </descriptors>
+ <finalName>qpid-${pom.version}</finalName>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+
+ </build>
+
+<profiles>
+ <profile>
+ <id>tests</id>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.qpid</groupId>
+ <artifactId>qpid-client</artifactId>
+ <type>test-jar</type>
+ <version>${project.version}</version>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <artifactId>maven-assembly-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>distribution-package</id>
+ <phase>package</phase>
+ <goals>
+ <goal>single</goal>
+ </goals>
+ <configuration>
+ <descriptors>
+ <descriptor>src/main/assembly/client-bin-tests.xml</descriptor>
+ </descriptors>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+ </profile>
+</profiles>
+
+</project>
diff --git a/java/distribution/src/main/assembly/client-bin.xml b/java/client/distribution/src/main/assembly/client-bin-tests.xml
index f89b1a39d2..ec4df1c9a7 100644
--- a/java/distribution/src/main/assembly/client-bin.xml
+++ b/java/client/distribution/src/main/assembly/client-bin-tests.xml
@@ -18,55 +18,74 @@
* under the License.
-->
<assembly>
- <id>java-client-bin</id>
+ <id>java-client-bin-with-tests</id>
<includeBaseDirectory>false</includeBaseDirectory>
<formats>
<format>tar.gz</format>
<format>zip</format>
</formats>
- <moduleSets>
- <moduleSet>
- <includes>
- <include>org.apache.qpid:client</include>
- </includes>
- <binaries>
- <includeDependencies>true</includeDependencies>
- <unpack>false</unpack>
- </binaries>
- </moduleSet>
- </moduleSets>
-
<fileSets>
<fileSet>
- <directory>src/main/release</directory>
+ <!-- Apache license files -->
+ <directory>../../resources</directory>
<outputDirectory>qpid-${qpid.version}</outputDirectory>
<includes>
<include>DISCLAIMER</include>
+ <include>LICENSE.txt</include>
+ <include>NOTICE.txt</include>
+ <include>README.txt</include>
</includes>
</fileSet>
+
<fileSet>
+ <directory>../../release-docs</directory>
+ <outputDirectory>qpid-${qpid.version}/docs</outputDirectory>
+ <includes>
+ <include>RELEASE_NOTES.txt</include>
+ </includes>
+ </fileSet>
+
+ <!-- Include easy access to test source-->
+ <fileSet>
+ <directory>../src/test</directory>
+ <outputDirectory>qpid-${qpid.version}/src</outputDirectory>
+ <includes>
+ <include>**/*.java</include>
+ </includes>
+ </fileSet>
+
+ <!-- fileSet> Client contains a readme.txt as does qpid root.
+ Which will cause problems on windows as the zip will
+ contain: readme.txt and README.txt
+ < Client local documentation>
<directory>..</directory>
<outputDirectory>qpid-${qpid.version}</outputDirectory>
<includes>
<include>*.txt</include>
</includes>
- </fileSet>
- <fileSet>
- <directory>src/main/release/etc</directory>
+ </fileSet-->
+
+ <!-- Configuration -->
+ <fileSet>
+ <directory>../test/etc</directory>
<outputDirectory>qpid-${qpid.version}/etc</outputDirectory>
<includes>
- <include>logging.properties</include>
- <include>log4j.properties</include>
+ <include>**/*</include>
</includes>
- </fileSet>
- <fileSet>
- <directory>src/main/release/docs</directory>
- <outputDirectory>qpid-${qpid.version}/docs</outputDirectory>
+ </fileSet>
+
+ <!-- Execution Scripts -->
+ <fileSet>
+ <directory>../test/bin</directory>
+ <outputDirectory>qpid-${qpid.version}/bin</outputDirectory>
<includes>
- <include>RELEASE_NOTES.txt</include>
+ <include>**/*</include>
</includes>
- </fileSet>
+ <fileMode>777</fileMode> <!-- RWX -->
+ </fileSet>
+
+ <!-- Metadata Jar -->
<fileSet>
<directory>target</directory>
<outputDirectory>qpid-${qpid.version}/lib</outputDirectory>
@@ -80,29 +99,9 @@
<dependencySet>
<outputDirectory>qpid-${qpid.version}/lib</outputDirectory>
<unpack>false</unpack>
- <excludes>
- <exclude>org.apache.qpid:qpid-distribution</exclude>
- <exclude>org.apache.qpid.management:org.apache.qpid.management.ui</exclude>
- <exclude>org.eclipse.core:org.eclipse.core.commands</exclude>
- <exclude>org.eclipse.core:org.eclipse.core.contenttype</exclude>
- <exclude>org.eclipse.core:org.eclipse.core.expressions</exclude>
- <exclude>org.eclipse.core:org.eclipse.core.jobs</exclude>
- <exclude>org.eclipse.core:org.eclipse.core.runtime</exclude>
- <exclude>org.eclipse.core:org.eclipse.core.runtime.compatibility.auth</exclude>
- <exclude>org.eclipse.core:org.eclipse.core.runtime.compatibility.registry</exclude>
- <exclude>org.eclipse.equinox:org.eclipse.equinox.common</exclude>
- <exclude>org.eclipse.equinox:org.eclipse.equinox.preferences</exclude>
- <exclude>org.eclipse.equinox:org.eclipse.equinox.registry</exclude>
- <exclude>org.eclipse.help:org.eclipse.help</exclude>
- <exclude>org.eclipse.jface:org.eclipse.jface</exclude>
- <exclude>org.eclipse.osgi:org.eclipse.osgi</exclude>
- <exclude>org.eclipse.swt:org.eclipse.swt</exclude>
- <exclude>org.eclipse.swt:org.eclipse.swt.win32.win32.x86</exclude>
- <exclude>org.eclipse.ui:org.eclipse.ui</exclude>
- <exclude>org.eclipse.ui:org.eclipse.ui.forms</exclude>
- <exclude>org.eclipse.ui:org.eclipse.ui.workbench</exclude>
+ <excludes>
+ <exclude>org.apache.qpid:qpid-client-distribution</exclude>
</excludes>
- <scope>runtime</scope>
</dependencySet>
</dependencySets>
</assembly>
diff --git a/java/client/distribution/src/main/assembly/client-bin.xml b/java/client/distribution/src/main/assembly/client-bin.xml
new file mode 100644
index 0000000000..962f084995
--- /dev/null
+++ b/java/client/distribution/src/main/assembly/client-bin.xml
@@ -0,0 +1,76 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ * 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.
+-->
+<assembly>
+ <id>java-client-bin</id>
+ <includeBaseDirectory>false</includeBaseDirectory>
+ <formats>
+ <format>tar.gz</format>
+ <format>zip</format>
+ </formats>
+
+ <fileSets>
+ <fileSet>
+ <!-- Apache license files -->
+ <directory>../../resources</directory>
+ <outputDirectory>qpid-${qpid.version}</outputDirectory>
+ <includes>
+ <include>DISCLAIMER</include>
+ <include>LICENSE.txt</include>
+ <include>NOTICE.txt</include>
+ <include>README.txt</include>
+ </includes>
+ </fileSet>
+
+ <!--fileSet>
+ < Client local documentation>
+ <directory>..</directory>
+ <outputDirectory>qpid-${qpid.version}</outputDirectory>
+ <includes>
+ <include>*.txt</include>
+ </includes>
+ </fileSet-->
+
+ <fileSet>
+ <directory>../../release-docs</directory>
+ <outputDirectory>qpid-${qpid.version}/docs</outputDirectory>
+ <includes>
+ <include>RELEASE_NOTES.txt</include>
+ </includes>
+ </fileSet>
+
+ <fileSet>
+ <directory>target</directory>
+ <outputDirectory>qpid-${qpid.version}/lib</outputDirectory>
+ <includes>
+ <include>qpid-incubating.jar</include>
+ </includes>
+ </fileSet>
+ </fileSets>
+
+ <dependencySets>
+ <dependencySet>
+ <outputDirectory>qpid-${qpid.version}/lib</outputDirectory>
+ <unpack>false</unpack>
+ <excludes>
+ <exclude>org.apache.qpid:qpid-client-distribution</exclude>
+ </excludes>
+ </dependencySet>
+ </dependencySets>
+</assembly>
diff --git a/java/client/distribution/src/main/assembly/client-src.xml b/java/client/distribution/src/main/assembly/client-src.xml
new file mode 100644
index 0000000000..b5055f05d7
--- /dev/null
+++ b/java/client/distribution/src/main/assembly/client-src.xml
@@ -0,0 +1,62 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ * 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.
+-->
+<assembly>
+ <!-- id typically identifies the "type" (src vs bin etc) of the assembly -->
+ <id>java-client-src</id>
+ <includeBaseDirectory>false</includeBaseDirectory>
+ <formats>
+ <format>tar.gz</format>
+ <format>zip</format>
+ </formats>
+
+ <fileSets>
+
+ <fileSet>
+ <!-- Apache license files -->
+ <directory>../../resources</directory>
+ <outputDirectory>qpid-${qpid.version}-src</outputDirectory>
+ <includes>
+ <include>DISCLAIMER</include>
+ <include>LICENSE.txt</include>
+ <include>NOTICE.txt</include>
+ <include>README.txt</include>
+ </includes>
+ </fileSet>
+
+ <fileSet>
+ <directory>..</directory>
+ <outputDirectory>qpid-${qpid.version}-src</outputDirectory>
+ <includes>
+ <include>src/main/**</include>
+ <include>src/test/**</include>
+ <include>test/main/**</include>
+ <include>test/test/**</include>
+ <include>pom.xml</include>
+ <include>distribution/**</include>
+ </includes>
+ <excludes>
+ <exclude>**/target</exclude>
+ <exclude>**/target/**/*</exclude>
+ <exclude>**/build</exclude>
+ <exclude>**/build/**/*</exclude>
+ </excludes>
+ </fileSet>
+ </fileSets>
+</assembly>
diff --git a/java/client/example/bin/set_classpath.bat b/java/client/example/bin/set_classpath.bat
new file mode 100644
index 0000000000..d528967024
--- /dev/null
+++ b/java/client/example/bin/set_classpath.bat
@@ -0,0 +1,50 @@
+@REM Licensed to the Apache Software Foundation (ASF) under one
+@REM or more contributor license agreements. See the NOTICE file
+@REM distributed with this work for additional information
+@REM regarding copyright ownership. The ASF licenses this file
+@REM to you under the Apache License, Version 2.0 (the
+@REM "License"); you may not use this file except in compliance
+@REM with the License. You may obtain a copy of the License at
+@REM
+@REM http://www.apache.org/licenses/LICENSE-2.0
+@REM
+@REM Unless required by applicable law or agreed to in writing,
+@REM software distributed under the License is distributed on an
+@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+@REM KIND, either express or implied. See the License for the
+@REM specific language governing permissions and limitations
+@REM under the License.
+
+@REM Helper script to set classpath for running Qpid example classes
+@REM NB: You must add the Qpid client and common jars to your CLASSPATH
+@REM before running this script
+
+@echo off
+
+if "%QPID_HOME%" == "" GOTO ERROR_QPID_HOME
+
+set QPIDLIB=%QPID_HOME%\lib
+
+if "%CLASSPATH%" == "" GOTO ERROR_CLASSPATH
+
+set CLASSPATH=%CLASSPATH%;%QPIDLIB%\backport-util-concurrent-2.2.jar
+set CLASSPATH=%CLASSPATH%;%QPIDLIB%\geronimo-jms_1.1_spec-1.0.jar
+set CLASSPATH=%CLASSPATH%;%QPIDLIB%\commons-collections-3.1.jar
+set CLASSPATH=%CLASSPATH%;%QPIDLIB%\commons-configuration-1.2.jar
+set CLASSPATH=%CLASSPATH%;%QPIDLIB%\commons-cli-1.0.jar
+set CLASSPATH=%CLASSPATH%;%QPIDLIB%\commons-lang-2.1.jar
+set CLASSPATH=%CLASSPATH%;%QPIDLIB%\commons-logging-api-1.0.4.jar
+set CLASSPATH=%CLASSPATH%;%QPIDLIB%\commons-logging-1.0.jar
+set CLASSPATH=%CLASSPATH%;%QPIDLIB%\log4j-1.2.12.jar
+set CLASSPATH=%CLASSPATH%;%QPIDLIB%\mina-core-1.0.0.jar
+set CLASSPATH=%CLASSPATH%;%QPIDLIB%\mina-filter-ssl-1.0.0.jar
+set CLASSPATH=%CLASSPATH%;%QPIDLIB%\mina-java5-1.0.0.jar
+set CLASSPATH=%CLASSPATH%;%QPIDLIB%\slf4j-simple-1.0.jar
+
+GOTO END
+
+:ERROR_CLASSPATH
+Echo Please set set your CLASSPATH variable to include the Qpid client and common jars. Exiting ....
+:ERROR_QPID_HOME
+Echo Please set QPID_HOME variable. Exiting ....
+:END
diff --git a/java/client/example/bin/set_classpath.sh b/java/client/example/bin/set_classpath.sh
new file mode 100755
index 0000000000..89e9bc8242
--- /dev/null
+++ b/java/client/example/bin/set_classpath.sh
@@ -0,0 +1,83 @@
+#!/bin/sh -xv
+#
+# 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.
+#
+
+# Helper script to set classpath for running Qpid example classes
+# NB: You must add the Qpid client and common jars to your CLASSPATH
+# before running this script
+
+
+cygwin=false
+if [[ "$(uname -a | fgrep Cygwin)" != "" ]]; then
+ cygwin=true
+fi
+
+#Should have set the QPID_HOME var after install to the working dir e.g. home/qpid/qpid-1.0-incubating-M2-SNAPSHOT
+if [ "$QPID_HOME" = "" ] ; then
+ echo "ERROR: Please set QPID_HOME variable. Exiting ...."
+ exit 1
+else
+ QPIDLIB=$QPID_HOME/lib
+fi
+
+if $cygwin; then
+ QPIDLIB=$(cygpath -w $QPIDLIB)
+fi
+
+if [ "$CLASSPATH" = "" ] ; then
+ echo "ERROR: Please set set your CLASSPATH variable to include the Qpid client and common jars. Exiting ...."
+ exit 2
+fi
+
+#Converts paths for cygwin if req
+#Some nasty concatenation to get round cygpath line limits
+if $cygwin; then
+ SEP=";"
+ CLASSPATH=`cygpath -w $CLASSPATH`
+ CLASSPATH=$CLASSPATH$SEP`cygpath -w $QPIDLIB/backport-util-concurrent-2.2.jar`
+ CLASSPATH=$CLASSPATH$SEP`cygpath -w $QPIDLIB/geronimo-jms_1.1_spec-1.0.jar`
+ CLASSPATH=$CLASSPATH$SEP`cygpath -w $QPIDLIB/commons-collections-3.1.jar`
+ CLASSPATH=$CLASSPATH$SEP`cygpath -w $QPIDLIB/commons-configuration-1.2.jar`
+ CLASSPATH=$CLASSPATH$SEP`cygpath -w $QPIDLIB/commons-cli-1.0.jar`
+ CLASSPATH=$CLASSPATH$SEP`cygpath -w $QPIDLIB/commons-lang-2.1.jar`
+ CLASSPATH=$CLASSPATH$SEP`cygpath -w $QPIDLIB/commons-logging-api-1.0.4.jar`
+ CLASSPATH=$CLASSPATH$SEP`cygpath -w $QPIDLIB/commons-logging-1.0.jar`
+ CLASSPATH=$CLASSPATH$SEP`cygpath -w $QPIDLIB/log4j-1.2.12.jar`
+ CLASSPATH=$CLASSPATH$SEP`cygpath -w $QPIDLIB/mina-core-1.0.0.jar`
+ CLASSPATH=$CLASSPATH$SEP`cygpath -w $QPIDLIB/mina-filter-ssl-1.0.0.jar`
+ CLASSPATH=$CLASSPATH$SEP`cygpath -w $QPIDLIB/mina-java5-1.0.0.jar`
+ CLASSPATH=$CLASSPATH$SEP`cygpath -w $QPIDLIB/slf4j-simple-1.0.jar`
+ export CLASSPATH
+else
+ CLASSPATH=$CLASSPATH:$QPIDLIB/backport-util-concurrent-2.2.jar
+ CLASSPATH=$CLASSPATH:$QPIDLIB/geronimo-jms_1.1_spec-1.0.jar
+ CLASSPATH=$CLASSPATH:$QPIDLIB/commons-collections-3.1.jar
+ CLASSPATH=$CLASSPATH:$QPIDLIB/commons-configuration-1.2.jar
+ CLASSPATH=$CLASSPATH:$QPIDLIB/commons-cli-1.0.jar
+ CLASSPATH=$CLASSPATH:$QPIDLIB/commons-lang-2.1.jar
+ CLASSPATH=$CLASSPATH:$QPIDLIB/commons-logging-api-1.0.4.jar
+ CLASSPATH=$CLASSPATH:$QPIDLIB/commons-logging-1.0.jar
+ CLASSPATH=$CLASSPATH:$QPIDLIB/log4j-1.2.12.jar
+ CLASSPATH=$CLASSPATH:$QPIDLIB/mina-core-1.0.0.jar
+ CLASSPATH=$CLASSPATH:$QPIDLIB/mina-filter-ssl-1.0.0.jar
+ CLASSPATH=$CLASSPATH:$QPIDLIB/mina-java5-1.0.0.jar
+ CLASSPATH=$CLASSPATH:$QPIDLIB/slf4j-simple-1.0.jar
+ export CLASSPATH
+fi
+
diff --git a/java/client/pom.xml b/java/client/pom.xml
index e45aad733d..854428fb39 100644
--- a/java/client/pom.xml
+++ b/java/client/pom.xml
@@ -35,40 +35,45 @@
<properties>
<topDirectoryLocation>..</topDirectoryLocation>
+ <java.source.version>1.5</java.source.version>
+ <qpid.version>${pom.version}</qpid.version>
+ <qpid.targetDir>${project.build.directory}</qpid.targetDir>
</properties>
<dependencies>
+
<dependency>
<groupId>org.apache.qpid</groupId>
<artifactId>qpid-common</artifactId>
</dependency>
- <dependency>
- <groupId>org.apache.qpid</groupId>
- <artifactId>qpid-broker</artifactId>
- </dependency>
-
- <dependency>
- <groupId>commons-codec</groupId>
- <artifactId>commons-codec</artifactId>
- </dependency>
<dependency>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-jms_1.1_spec</artifactId>
</dependency>
+
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
</dependency>
+
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
</dependency>
+
<dependency>
<groupId>org.apache.mina</groupId>
<artifactId>mina-filter-ssl</artifactId>
</dependency>
+ <!-- Test Dependencies -->
+ <dependency> <!-- for inVm Broker -->
+ <groupId>org.apache.qpid</groupId>
+ <artifactId>qpid-broker</artifactId>
+ <scope>test</scope>
+ </dependency>
+
<dependency>
<groupId>jmscts</groupId>
<artifactId>jmscts</artifactId>
@@ -85,12 +90,14 @@
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
+ <scope>test</scope>
</dependency>
+
<dependency>
<groupId>org.easymock</groupId>
<artifactId>easymockclassextension</artifactId>
+ <scope>test</scope>
</dependency>
-
</dependencies>
<build>
@@ -115,11 +122,67 @@
</property>
<property>
<name>log4j.configuration</name>
- <value>file:///${basedir}/src/main/java/log4j.properties</value>
+ <value>file:///${basedir}/src/main/java/client.log4j</value>
</property>
</systemProperties>
</configuration>
</plugin>
+
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-jar-plugin</artifactId>
+ <executions>
+ <execution>
+ <phase>package</phase>
+ <goals>
+ <goal>test-jar</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+
</plugins>
+
+<!-- The inclusion of this resource causes the build to hang. -->
+ <!--resources>
+ <resource>
+ <targetPath>META-INF/</targetPath>
+ <filtering>false</filtering>
+ <directory>../resources/META-INF</directory>
+ <includes>
+ <include>**</include>
+ </includes>
+ </resource>
+ </resources-->
+
+ <testResources>
+ <testResource>
+ <targetPath>META-INF/</targetPath>
+ <filtering>false</filtering>
+ <directory>../resources/META-INF</directory>
+ <includes>
+ <include>**</include>
+ </includes>
+ </testResource>
+ <testResource>
+ <targetPath>src/</targetPath>
+ <filtering>false</filtering>
+ <directory>src/test/java</directory>
+ <includes>
+ <include>**/*.java</include>
+ </includes>
+ </testResource>
+
+ <testResource>
+ <targetPath></targetPath>
+ <filtering>false</filtering>
+ <directory>src/main/java</directory>
+ <includes>
+ <include>client.log4j</include>
+ </includes>
+ </testResource>
+ </testResources>
+
</build>
+
</project>
diff --git a/java/client/readme.txt b/java/client/readme.txt
deleted file mode 100644
index ef8fa01717..0000000000
--- a/java/client/readme.txt
+++ /dev/null
@@ -1,31 +0,0 @@
-AMQP JMS API
-
-To build this you will need ant. The build.xml file requires that the amq.home
-property be set to point to the location of the root directory under which the
-base2 and amqp moduels reside (these contain protocol definitions used in
-the code generation).
-
-You can avoid setting it if you have the following structure:
-
- root/
- base/
- base2/
- foreign/
- gsl/
- amqp/
- blaze/
- java/
- client
- build.xml
- Readme.txt [this file]
- common
-
-
-Otherwise you can either pass it in on the command line or add it to a file
-named build.properties in the same directory as this Readme.txt file.
-
-E.g.:
-
-ant -Damq.home=c:\AMQP\
-
-
diff --git a/java/systests/src/test/java/log4j.properties b/java/client/src/main/java/client.log4j
index 6d596d1d19..525433e9a9 100644
--- a/java/systests/src/test/java/log4j.properties
+++ b/java/client/src/main/java/client.log4j
@@ -1,28 +1,28 @@
-#
-# 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.
-#
-log4j.rootLogger=${root.logging.level}
-
-
-log4j.logger.org.apache.qpid=${amqj.logging.level}, console
-log4j.additivity.org.apache.qpid=false
-
-log4j.appender.console=org.apache.log4j.ConsoleAppender
-log4j.appender.console.Threshold=all
-log4j.appender.console.layout=org.apache.log4j.PatternLayout
-log4j.appender.console.layout.ConversionPattern=%t %d %p [%c{4}] %m%n
+#
+# 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.
+#
+log4j.rootLogger=${root.logging.level}
+
+
+log4j.logger.org.apache.qpid=${amqj.logging.level}, console
+log4j.additivity.org.apache.qpid=false
+
+log4j.appender.console=org.apache.log4j.ConsoleAppender
+log4j.appender.console.Threshold=all
+log4j.appender.console.layout=org.apache.log4j.PatternLayout
+log4j.appender.console.layout.ConversionPattern=%t %d %p [%c{4}] %m%n
diff --git a/java/client/src/main/java/org/apache/qpid/client/AMQBrokerDetails.java b/java/client/src/main/java/org/apache/qpid/client/AMQBrokerDetails.java
index 6da0da9f6f..8fb87f9e64 100644
--- a/java/client/src/main/java/org/apache/qpid/client/AMQBrokerDetails.java
+++ b/java/client/src/main/java/org/apache/qpid/client/AMQBrokerDetails.java
@@ -308,7 +308,7 @@ public class AMQBrokerDetails implements BrokerDetails
}
}
- //remove the extra DEFAULT_OPTION_SEPERATOR or the '?' if there are no options
+ //removeKey the extra DEFAULT_OPTION_SEPERATOR or the '?' if there are no options
optionsURL.deleteCharAt(optionsURL.length() - 1);
return optionsURL.toString();
@@ -334,4 +334,15 @@ public class AMQBrokerDetails implements BrokerDetails
}
+ public static String checkTransport(String broker)
+ {
+ if ((!broker.contains("://")))
+ {
+ return "tcp://" + broker;
+ }
+ else
+ {
+ return broker;
+ }
+ }
}
diff --git a/java/client/src/main/java/org/apache/qpid/client/AMQConnection.java b/java/client/src/main/java/org/apache/qpid/client/AMQConnection.java
index bb3c33f2fe..f20a3f7d1f 100644
--- a/java/client/src/main/java/org/apache/qpid/client/AMQConnection.java
+++ b/java/client/src/main/java/org/apache/qpid/client/AMQConnection.java
@@ -30,6 +30,7 @@ import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
import javax.jms.ConnectionConsumer;
import javax.jms.ConnectionMetaData;
@@ -156,21 +157,30 @@ public class AMQConnection extends Closeable implements Connection, QueueConnect
// Keeps a tally of connections for logging and debugging
- private static AtomicInteger _ConnectionId;
- static { _ConnectionId = new AtomicInteger(0); }
+ private static AtomicLong _ConnectionId;
+ static { _ConnectionId = new AtomicLong(0); }
/*
* The connection meta data
*/
private QpidConnectionMetaData _connectionMetaData;
+ /**
+ * @param broker brokerdetails
+ * @param username username
+ * @param password password
+ * @param clientName clientid
+ * @param virtualHost virtualhost
+ * @throws AMQException
+ * @throws URLSyntaxException
+ */
public AMQConnection(String broker, String username, String password,
String clientName, String virtualHost) throws AMQException, URLSyntaxException
{
this(new AMQConnectionURL(ConnectionURL.AMQ_PROTOCOL + "://" +
username + ":" + password + "@" +
- (clientName==null?"":clientName) +
- virtualHost + "?brokerlist='" + broker + "'"));
+ (clientName == null ? "" : clientName) + "/" +
+ virtualHost + "?brokerlist='" + AMQBrokerDetails.checkTransport(broker) + "'"));
}
public AMQConnection(String host, int port, String username, String password,
@@ -185,12 +195,12 @@ public class AMQConnection extends Closeable implements Connection, QueueConnect
this(new AMQConnectionURL(useSSL ?
ConnectionURL.AMQ_PROTOCOL + "://" +
username + ":" + password + "@" +
- (clientName==null?"":clientName) +
+ (clientName == null ? "" : clientName) +
virtualHost + "?brokerlist='tcp://" + host + ":" + port + "'"
+ "," + ConnectionURL.OPTIONS_SSL + "='true'" :
ConnectionURL.AMQ_PROTOCOL + "://" +
username + ":" + password + "@" +
- (clientName==null?"":clientName) +
+ (clientName == null ? "" : clientName) +
virtualHost + "?brokerlist='tcp://" + host + ":" + port + "'"
+ "," + ConnectionURL.OPTIONS_SSL + "='false'"
));
@@ -215,7 +225,7 @@ public class AMQConnection extends Closeable implements Connection, QueueConnect
_clientName = connectionURL.getClientName();
_username = connectionURL.getUsername();
_password = connectionURL.getPassword();
- _virtualHost = connectionURL.getVirtualHost();
+ setVirtualHost(connectionURL.getVirtualHost());
_failoverPolicy = new FailoverPolicy(connectionURL);
@@ -326,6 +336,15 @@ public class AMQConnection extends Closeable implements Connection, QueueConnect
_clientName = clientName;
_username = username;
_password = password;
+ setVirtualHost(virtualHost);
+ }
+
+ private void setVirtualHost(String virtualHost)
+ {
+ if(virtualHost.startsWith("/"))
+ {
+ virtualHost = virtualHost.substring(1);
+ }
_virtualHost = virtualHost;
}
@@ -410,6 +429,12 @@ public class AMQConnection extends Closeable implements Connection, QueueConnect
return _failoverPolicy.failoverAllowed();
}
+ // Test purposes only - used for testing refs, which cannot be done using JMS interfaces
+ public AMQSession createAMQSession(final boolean transacted, final int acknowledgeMode) throws JMSException
+ {
+ return (AMQSession)createSession(transacted, acknowledgeMode, AMQSession.DEFAULT_PREFETCH_HIGH_MARK);
+ }
+
public Session createSession(final boolean transacted, final int acknowledgeMode) throws JMSException
{
return createSession(transacted, acknowledgeMode, AMQSession.DEFAULT_PREFETCH_HIGH_MARK);
@@ -484,20 +509,21 @@ public class AMQConnection extends Closeable implements Connection, QueueConnect
private void createChannelOverWire(int channelId, int prefetchHigh, int prefetchLow, boolean transacted)
throws AMQException
{
- // AMQP version change: Hardwire the version to 0-9 (major=0, minor=9)
- // TODO: Connect this to the session version obtained from ProtocolInitiation for this session.
// Be aware of possible changes to parameter order as versions change.
_protocolHandler.syncWrite(channelId,
- ChannelOpenBody.createMethodBody((byte)0, (byte)9, // AMQP version (major, minor)
+ ChannelOpenBody.createMethodBody(
+ _protocolHandler.getProtocolMajorVersion(), // AMQP major version
+ _protocolHandler.getProtocolMinorVersion(), // AMQP minor version
null), // outOfBand
ChannelOpenOkBody.class);
//todo send low water mark when protocol allows.
- // AMQP version change: Hardwire the version to 0-9 (major=0, minor=9)
- // TODO: Connect this to the session version obtained from ProtocolInitiation for this session.
+
// Be aware of possible changes to parameter order as versions change.
_protocolHandler.syncWrite(channelId,
- MessageQosBody.createMethodBody((byte)0, (byte)9, // AMQP version (major, minor)
+ MessageQosBody.createMethodBody(
+ _protocolHandler.getProtocolMajorVersion(), // AMQP major version
+ _protocolHandler.getProtocolMinorVersion(), // AMQP minor version
false, // global
prefetchHigh, // prefetchCount
0), // prefetchSize
@@ -509,10 +535,11 @@ public class AMQConnection extends Closeable implements Connection, QueueConnect
{
_logger.debug("Issuing TxSelect for " + channelId);
}
- // AMQP version change: Hardwire the version to 0-9 (major=0, minor=9)
- // TODO: Connect this to the session version obtained from ProtocolInitiation for this session.
// Be aware of possible changes to parameter order as versions change.
- _protocolHandler.syncWrite(channelId, TxSelectBody.createMethodBody((byte)0, (byte)9), TxSelectOkBody.class);
+ _protocolHandler.syncWrite(channelId, TxSelectBody.createMethodBody(
+ _protocolHandler.getProtocolMajorVersion(), // AMQP major version
+ _protocolHandler.getProtocolMinorVersion()), // AMQP minor version
+ TxSelectOkBody.class);
}
}
@@ -544,6 +571,7 @@ public class AMQConnection extends Closeable implements Connection, QueueConnect
/**
* Returns an AMQQueueSessionAdaptor which wraps an AMQSession and throws IllegalStateExceptions
* where specified in the JMS spec
+ *
* @param transacted
* @param acknowledgeMode
* @return QueueSession
@@ -557,6 +585,7 @@ public class AMQConnection extends Closeable implements Connection, QueueConnect
/**
* Returns an AMQTopicSessionAdapter which wraps an AMQSession and throws IllegalStateExceptions
* where specified in the JMS spec
+ *
* @param transacted
* @param acknowledgeMode
* @return TopicSession
@@ -591,7 +620,7 @@ public class AMQConnection extends Closeable implements Connection, QueueConnect
{
checkNotClosed();
return _connectionMetaData;
-
+
}
public ExceptionListener getExceptionListener() throws JMSException
@@ -642,13 +671,18 @@ public class AMQConnection extends Closeable implements Connection, QueueConnect
public void close() throws JMSException
{
- synchronized(getFailoverMutex())
+ close(-1);
+ }
+
+ public void close(long timeout) throws JMSException
+ {
+ synchronized (getFailoverMutex())
{
if (!_closed.getAndSet(true))
{
try
{
- closeAllSessions(null);
+ closeAllSessions(null, timeout);
_protocolHandler.closeConnection();
}
catch (AMQException e)
@@ -686,7 +720,7 @@ public class AMQConnection extends Closeable implements Connection, QueueConnect
* <p/>
* The caller must hold the failover mutex before calling this method.
*/
- private void closeAllSessions(Throwable cause) throws JMSException
+ private void closeAllSessions(Throwable cause, long timeout) throws JMSException
{
final LinkedList sessionCopy = new LinkedList(_sessions.values());
final Iterator it = sessionCopy.iterator();
@@ -702,7 +736,7 @@ public class AMQConnection extends Closeable implements Connection, QueueConnect
{
try
{
- session.close();
+ session.close(timeout);
}
catch (JMSException e)
{
@@ -920,7 +954,7 @@ public class AMQConnection extends Closeable implements Connection, QueueConnect
{
if (cause instanceof AMQException)
{
- je = new JMSException(Integer.toString(((AMQException)cause).getErrorCode()) ,"Exception thrown against " + toString() + ": " + cause);
+ je = new JMSException(Integer.toString(((AMQException) cause).getErrorCode()), "Exception thrown against " + toString() + ": " + cause);
}
else
{
@@ -951,7 +985,7 @@ public class AMQConnection extends Closeable implements Connection, QueueConnect
{
_logger.info("Closing AMQConnection due to :" + cause.getMessage());
_closed.set(true);
- closeAllSessions(cause); // FIXME: when doing this end up with RejectedExecutionException from executor.
+ closeAllSessions(cause, -1); // FIXME: when doing this end up with RejectedExecutionException from executor.
}
catch (JMSException e)
{
@@ -973,8 +1007,8 @@ public class AMQConnection extends Closeable implements Connection, QueueConnect
void deregisterSession(int channelId)
{
_sessions.remove(channelId);
- }
-
+ }
+
/**
* For all sessions, and for all consumers in those sessions, resubscribe. This is called during failover handling.
* The caller must hold the failover mutex before calling this method.
@@ -982,7 +1016,7 @@ public class AMQConnection extends Closeable implements Connection, QueueConnect
public void resubscribeSessions() throws JMSException, AMQException
{
ArrayList sessions = new ArrayList(_sessions.values());
- _logger.info(MessageFormat.format("Resubscribing sessions = {0} sessions.size={1}", sessions, sessions.size())); // FIXME: remove?
+ _logger.info(MessageFormat.format("Resubscribing sessions = {0} sessions.size={1}", sessions, sessions.size())); // FIXME: removeKey?
for (Iterator it = sessions.iterator(); it.hasNext();)
{
AMQSession s = (AMQSession) it.next();
@@ -1025,7 +1059,7 @@ public class AMQConnection extends Closeable implements Connection, QueueConnect
null); // factory location
}
- public int getConnectionId()
+ public long getConnectionId()
{
return _ConnectionId.get();
}
diff --git a/java/client/src/main/java/org/apache/qpid/client/AMQDestination.java b/java/client/src/main/java/org/apache/qpid/client/AMQDestination.java
index c6f3f9c492..bc9e7137dc 100644
--- a/java/client/src/main/java/org/apache/qpid/client/AMQDestination.java
+++ b/java/client/src/main/java/org/apache/qpid/client/AMQDestination.java
@@ -25,6 +25,7 @@ import org.apache.qpid.url.AMQBindingURL;
import org.apache.qpid.url.URLSyntaxException;
import org.apache.qpid.url.URLHelper;
import org.apache.qpid.exchange.ExchangeDefaults;
+import org.apache.qpid.framing.AMQShortString;
import javax.naming.Reference;
import javax.naming.NamingException;
@@ -35,19 +36,31 @@ import javax.jms.Destination;
public abstract class AMQDestination implements Destination, Referenceable
{
- protected final String _exchangeName;
+ protected final AMQShortString _exchangeName;
- protected final String _exchangeClass;
+ protected final AMQShortString _exchangeClass;
- protected final String _destinationName;
+ protected final AMQShortString _destinationName;
- protected boolean _isDurable;
+ protected final boolean _isDurable;
protected final boolean _isExclusive;
protected final boolean _isAutoDelete;
- protected String _queueName;
+ private AMQShortString _queueName;
+
+ private String _url;
+ private AMQShortString _urlAsShortString;
+
+ private byte[] _byteEncoding;
+ private static final int IS_DURABLE_MASK = 0x1;
+ private static final int IS_EXCLUSIVE_MASK = 0x2;
+ private static final int IS_AUTODELETE_MASK = 0x4;
+
+ public static final byte QUEUE_TYPE = 1;
+ public static final byte TOPIC_TYPE = 2;
+ public static final byte UNKNOWN_TYPE = 3;
protected AMQDestination(String url) throws URLSyntaxException
{
@@ -63,27 +76,27 @@ public abstract class AMQDestination implements Destination, Referenceable
_isExclusive = Boolean.parseBoolean(binding.getOption(BindingURL.OPTION_EXCLUSIVE));
_isAutoDelete = Boolean.parseBoolean(binding.getOption(BindingURL.OPTION_AUTODELETE));
_isDurable = Boolean.parseBoolean(binding.getOption(BindingURL.OPTION_DURABLE));
- _queueName = binding.getQueueName();
+ _queueName = new AMQShortString(binding.getQueueName());
}
- protected AMQDestination(String exchangeName, String exchangeClass, String destinationName, String queueName)
+ protected AMQDestination(AMQShortString exchangeName, AMQShortString exchangeClass, AMQShortString destinationName, AMQShortString queueName)
{
this(exchangeName, exchangeClass, destinationName, false, false, queueName);
}
- protected AMQDestination(String exchangeName, String exchangeClass, String destinationName)
+ protected AMQDestination(AMQShortString exchangeName, AMQShortString exchangeClass, AMQShortString destinationName)
{
this(exchangeName, exchangeClass, destinationName, false, false, null);
}
- protected AMQDestination(String exchangeName, String exchangeClass, String destinationName, boolean isExclusive,
- boolean isAutoDelete, String queueName)
+ protected AMQDestination(AMQShortString exchangeName, AMQShortString exchangeClass, AMQShortString destinationName, boolean isExclusive,
+ boolean isAutoDelete, AMQShortString queueName)
{
this(exchangeName, exchangeClass, destinationName, isExclusive, isAutoDelete, queueName, false);
}
- protected AMQDestination(String exchangeName, String exchangeClass, String destinationName, boolean isExclusive,
- boolean isAutoDelete, String queueName, boolean isDurable)
+ protected AMQDestination(AMQShortString exchangeName, AMQShortString exchangeClass, AMQShortString destinationName, boolean isExclusive,
+ boolean isAutoDelete, AMQShortString queueName, boolean isDurable)
{
if (destinationName == null)
{
@@ -106,9 +119,13 @@ public abstract class AMQDestination implements Destination, Referenceable
_isDurable = isDurable;
}
- public String getEncodedName()
+ public AMQShortString getEncodedName()
{
- return toURL();
+ if(_urlAsShortString == null)
+ {
+ toURL();
+ }
+ return _urlAsShortString;
}
public boolean isDurable()
@@ -116,12 +133,12 @@ public abstract class AMQDestination implements Destination, Referenceable
return _isDurable;
}
- public String getExchangeName()
+ public AMQShortString getExchangeName()
{
return _exchangeName;
}
- public String getExchangeClass()
+ public AMQShortString getExchangeClass()
{
return _exchangeClass;
}
@@ -136,22 +153,34 @@ public abstract class AMQDestination implements Destination, Referenceable
return ExchangeDefaults.DIRECT_EXCHANGE_NAME.equals(_exchangeName);
}
- public String getDestinationName()
+ public AMQShortString getDestinationName()
{
return _destinationName;
}
public String getQueueName()
{
+ return _queueName == null ? null : _queueName.toString();
+ }
+
+ public AMQShortString getAMQQueueName()
+ {
return _queueName;
}
- public void setQueueName(String queueName)
+
+
+ public void setQueueName(AMQShortString queueName)
{
+
_queueName = queueName;
+ // calculated URL now out of date
+ _url = null;
+ _urlAsShortString = null;
+ _byteEncoding = null;
}
- public abstract String getRoutingKey();
+ public abstract AMQShortString getRoutingKey();
public boolean isExclusive()
{
@@ -179,53 +208,114 @@ public abstract class AMQDestination implements Destination, Referenceable
public String toURL()
{
- StringBuffer sb = new StringBuffer();
+ String url = _url;
+ if(url == null)
+ {
- sb.append(_exchangeClass);
- sb.append("://");
- sb.append(_exchangeName);
- sb.append("/");
+ StringBuffer sb = new StringBuffer();
- if (_destinationName != null)
- {
- sb.append(_destinationName);
- }
+ sb.append(_exchangeClass);
+ sb.append("://");
+ sb.append(_exchangeName);
- sb.append("/");
+ sb.append('/');
- if (_queueName != null)
- {
- sb.append(_queueName);
- }
+ if (_destinationName != null)
+ {
+ sb.append(_destinationName);
+ }
- sb.append("?");
+ sb.append('/');
- if (_isDurable)
- {
- sb.append(BindingURL.OPTION_DURABLE);
- sb.append("='true'");
- sb.append(URLHelper.DEFAULT_OPTION_SEPERATOR);
- }
+ if (_queueName != null)
+ {
+ sb.append(_queueName);
+ }
- if (_isExclusive)
- {
- sb.append(BindingURL.OPTION_EXCLUSIVE);
- sb.append("='true'");
- sb.append(URLHelper.DEFAULT_OPTION_SEPERATOR);
- }
+ sb.append('?');
- if (_isAutoDelete)
- {
- sb.append(BindingURL.OPTION_AUTODELETE);
- sb.append("='true'");
- sb.append(URLHelper.DEFAULT_OPTION_SEPERATOR);
+ if (_isDurable)
+ {
+ sb.append(BindingURL.OPTION_DURABLE);
+ sb.append("='true'");
+ sb.append(URLHelper.DEFAULT_OPTION_SEPERATOR);
+ }
+
+ if (_isExclusive)
+ {
+ sb.append(BindingURL.OPTION_EXCLUSIVE);
+ sb.append("='true'");
+ sb.append(URLHelper.DEFAULT_OPTION_SEPERATOR);
+ }
+
+ if (_isAutoDelete)
+ {
+ sb.append(BindingURL.OPTION_AUTODELETE);
+ sb.append("='true'");
+ sb.append(URLHelper.DEFAULT_OPTION_SEPERATOR);
+ }
+
+ //removeKey the last char '?' if there is no options , ',' if there are.
+ sb.deleteCharAt(sb.length() - 1);
+ url = sb.toString();
+ _url = url;
+ _urlAsShortString = new AMQShortString(url);
}
+ return url;
+ }
- //remove the last char '?' if there is no options , ',' if there are.
- sb.deleteCharAt(sb.length() - 1);
+ public byte[] toByteEncoding()
+ {
+ byte[] encoding = _byteEncoding;
+ if(encoding == null)
+ {
+ int size = _exchangeClass.length() + 1 +
+ _exchangeName.length() + 1 +
+ (_destinationName == null ? 0 : _destinationName.length()) + 1 +
+ (_queueName == null ? 0 : _queueName.length()) + 1 +
+ 1;
+ encoding = new byte[size];
+ int pos = 0;
+
+ pos = _exchangeClass.writeToByteArray(encoding, pos);
+ pos = _exchangeName.writeToByteArray(encoding, pos);
+ if(_destinationName == null)
+ {
+ encoding[pos++] = (byte)0;
+ }
+ else
+ {
+ pos = _destinationName.writeToByteArray(encoding,pos);
+ }
+ if(_queueName == null)
+ {
+ encoding[pos++] = (byte)0;
+ }
+ else
+ {
+ pos = _queueName.writeToByteArray(encoding,pos);
+ }
+ byte options = 0;
+ if(_isDurable)
+ {
+ options |= IS_DURABLE_MASK;
+ }
+ if(_isExclusive)
+ {
+ options |= IS_EXCLUSIVE_MASK;
+ }
+ if(_isAutoDelete)
+ {
+ options |= IS_AUTODELETE_MASK;
+ }
+ encoding[pos] = options;
+
+
+ _byteEncoding = encoding;
- return sb.toString();
+ }
+ return encoding;
}
public boolean equals(Object o)
@@ -258,7 +348,7 @@ public abstract class AMQDestination implements Destination, Referenceable
{
return false;
}
- if (_isExclusive != that._isExclusive)
+ /* if (_isExclusive != that._isExclusive)
{
return false;
}
@@ -266,6 +356,7 @@ public abstract class AMQDestination implements Destination, Referenceable
{
return false;
}
+ */
return true;
}
@@ -279,8 +370,8 @@ public abstract class AMQDestination implements Destination, Referenceable
{
result = 29 * result + _queueName.hashCode();
}
- result = result * (_isExclusive ? 13 : 7);
- result = result * (_isAutoDelete ? 13 : 7);
+// result = result * (_isExclusive ? 13 : 7);
+// result = result * (_isAutoDelete ? 13 : 7);
return result;
}
@@ -293,9 +384,55 @@ public abstract class AMQDestination implements Destination, Referenceable
null); // factory location
}
+
+ public static Destination createDestination(byte[] byteEncodedDestination)
+ {
+ AMQShortString exchangeClass;
+ AMQShortString exchangeName;
+ AMQShortString destinationName;
+ AMQShortString queueName;
+ boolean isDurable;
+ boolean isExclusive;
+ boolean isAutoDelete;
+
+ int pos = 0;
+ exchangeClass = AMQShortString.readFromByteArray(byteEncodedDestination, pos);
+ pos+= exchangeClass.length() + 1;
+ exchangeName = AMQShortString.readFromByteArray(byteEncodedDestination, pos);
+ pos+= exchangeName.length() + 1;
+ destinationName = AMQShortString.readFromByteArray(byteEncodedDestination, pos);
+ pos+= (destinationName == null ? 0 : destinationName.length()) + 1;
+ queueName = AMQShortString.readFromByteArray(byteEncodedDestination, pos);
+ pos+= (queueName == null ? 0 : queueName.length()) + 1;
+ int options = byteEncodedDestination[pos];
+ isDurable = (options & IS_DURABLE_MASK) != 0;
+ isExclusive = (options & IS_EXCLUSIVE_MASK) != 0;
+ isAutoDelete = (options & IS_AUTODELETE_MASK) != 0;
+
+ if (exchangeClass.equals(ExchangeDefaults.DIRECT_EXCHANGE_CLASS))
+ {
+ return new AMQQueue(destinationName,queueName,isExclusive,isAutoDelete,isDurable);
+ }
+ else if (exchangeClass.equals(ExchangeDefaults.TOPIC_EXCHANGE_CLASS))
+ {
+ return new AMQTopic(destinationName,isAutoDelete,queueName,isDurable);
+ }
+ else if (exchangeClass.equals(ExchangeDefaults.HEADERS_EXCHANGE_CLASS))
+ {
+ return new AMQHeadersExchange(destinationName);
+ }
+ else
+ {
+ throw new IllegalArgumentException("Unknown Exchange Class:" + exchangeClass);
+ }
+
+
+
+ }
+
public static Destination createDestination(BindingURL binding)
{
- String type = binding.getExchangeClass();
+ AMQShortString type = binding.getExchangeClass();
if (type.equals(ExchangeDefaults.DIRECT_EXCHANGE_CLASS))
{
diff --git a/java/client/src/main/java/org/apache/qpid/client/AMQHeadersExchange.java b/java/client/src/main/java/org/apache/qpid/client/AMQHeadersExchange.java
index c6d21c0ea7..b3dea770fa 100644
--- a/java/client/src/main/java/org/apache/qpid/client/AMQHeadersExchange.java
+++ b/java/client/src/main/java/org/apache/qpid/client/AMQHeadersExchange.java
@@ -22,6 +22,7 @@ package org.apache.qpid.client;
import org.apache.qpid.exchange.ExchangeDefaults;
import org.apache.qpid.url.BindingURL;
+import org.apache.qpid.framing.AMQShortString;
/**
* A destination backed by a headers exchange
@@ -33,12 +34,17 @@ public class AMQHeadersExchange extends AMQDestination
this(binding.getExchangeName());
}
- public AMQHeadersExchange(String queueName)
+ public AMQHeadersExchange(String name)
+ {
+ this(new AMQShortString(name));
+ }
+
+ public AMQHeadersExchange(AMQShortString queueName)
{
super(queueName, ExchangeDefaults.HEADERS_EXCHANGE_CLASS, queueName, true, true, null);
}
- public String getRoutingKey()
+ public AMQShortString getRoutingKey()
{
return getDestinationName();
}
diff --git a/java/client/src/main/java/org/apache/qpid/client/AMQQueue.java b/java/client/src/main/java/org/apache/qpid/client/AMQQueue.java
index 6c0da6112a..5b4f4e015c 100644
--- a/java/client/src/main/java/org/apache/qpid/client/AMQQueue.java
+++ b/java/client/src/main/java/org/apache/qpid/client/AMQQueue.java
@@ -22,6 +22,7 @@ package org.apache.qpid.client;
import org.apache.qpid.url.BindingURL;
import org.apache.qpid.exchange.ExchangeDefaults;
+import org.apache.qpid.framing.AMQShortString;
import javax.jms.Queue;
@@ -42,11 +43,27 @@ public class AMQQueue extends AMQDestination implements Queue
* Create a reference to a non temporary queue. Note this does not actually imply the queue exists.
* @param name the name of the queue
*/
- public AMQQueue(String name)
+ public AMQQueue(AMQShortString name)
{
this(name, false);
}
+ public AMQQueue(AMQShortString exchangeName, AMQShortString routingKey, AMQShortString queueName)
+ {
+ super(exchangeName, ExchangeDefaults.DIRECT_EXCHANGE_CLASS, routingKey, false,
+ false, queueName, false); }
+
+
+ /**
+ * Create a reference to a non temporary queue. Note this does not actually imply the queue exists.
+ * @param name the name of the queue
+ */
+ public AMQQueue(String name)
+ {
+ this(new AMQShortString(name), false);
+ }
+
+
/**
* Create a queue with a specified name.
*
@@ -56,10 +73,23 @@ public class AMQQueue extends AMQDestination implements Queue
*/
public AMQQueue(String name, boolean temporary)
{
+ this(new AMQShortString(name),temporary);
+ }
+
+
+ /**
+ * Create a queue with a specified name.
+ *
+ * @param name the destination name (used in the routing key)
+ * @param temporary if true the broker will generate a queue name, also if true then the queue is autodeleted
+ * and exclusive
+ */
+ public AMQQueue(AMQShortString name, boolean temporary)
+ {
// queue name is set to null indicating that the broker assigns a name in the case of temporary queues
// temporary queues are typically used as response queues
- this(name, temporary?null:name, temporary, temporary);
- _isDurable = !temporary;
+ this(name, temporary?null:name, temporary, temporary, !temporary);
+
}
/**
@@ -69,16 +99,22 @@ public class AMQQueue extends AMQDestination implements Queue
* @param exclusive true if the queue should only permit a single consumer
* @param autoDelete true if the queue should be deleted automatically when the last consumers detaches
*/
- public AMQQueue(String destinationName, String queueName, boolean exclusive, boolean autoDelete)
+ public AMQQueue(AMQShortString destinationName, AMQShortString queueName, boolean exclusive, boolean autoDelete)
+ {
+ this(destinationName, queueName, exclusive, autoDelete, false);
+ }
+
+
+ public AMQQueue(AMQShortString destinationName, AMQShortString queueName, boolean exclusive, boolean autoDelete, boolean durable)
{
super(ExchangeDefaults.DIRECT_EXCHANGE_NAME, ExchangeDefaults.DIRECT_EXCHANGE_CLASS, destinationName, exclusive,
- autoDelete, queueName);
+ autoDelete, queueName, durable);
}
- public String getRoutingKey()
+ public AMQShortString getRoutingKey()
{
- return getQueueName();
+ return getAMQQueueName();
}
public boolean isNameRequired()
diff --git a/java/client/src/main/java/org/apache/qpid/client/AMQSession.java b/java/client/src/main/java/org/apache/qpid/client/AMQSession.java
index 8862c466cb..9027c1b29c 100644
--- a/java/client/src/main/java/org/apache/qpid/client/AMQSession.java
+++ b/java/client/src/main/java/org/apache/qpid/client/AMQSession.java
@@ -20,16 +20,6 @@
*/
package org.apache.qpid.client;
-import java.io.Serializable;
-import java.text.MessageFormat;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentLinkedQueue;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicInteger;
-
import javax.jms.BytesMessage;
import javax.jms.Destination;
import javax.jms.IllegalStateException;
@@ -60,16 +50,15 @@ import org.apache.qpid.AMQException;
import org.apache.qpid.AMQInvalidSelectorException;
import org.apache.qpid.AMQUndeliveredException;
import org.apache.qpid.client.failover.FailoverSupport;
-import org.apache.qpid.client.message.AbstractJMSMessage;
-import org.apache.qpid.client.message.JMSStreamMessage;
-import org.apache.qpid.client.message.MessageFactoryRegistry;
-import org.apache.qpid.client.message.UnprocessedMessage;
+import org.apache.qpid.client.message.*;
import org.apache.qpid.client.protocol.AMQProtocolHandler;
+import org.apache.qpid.protocol.AMQMethodEvent;
import org.apache.qpid.client.util.FlowControllingBlockingQueue;
import org.apache.qpid.common.AMQPFilterTypes;
import org.apache.qpid.exchange.ExchangeDefaults;
import org.apache.qpid.framing.AMQFrame;
import org.apache.qpid.framing.AMQMethodBody;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.framing.ChannelCloseBody;
import org.apache.qpid.framing.ChannelCloseOkBody;
import org.apache.qpid.framing.ChannelFlowBody;
@@ -93,10 +82,19 @@ import org.apache.qpid.framing.TxRollbackOkBody;
import org.apache.qpid.protocol.AMQMethodEvent;
import org.apache.qpid.jms.Session;
import org.apache.qpid.protocol.AMQConstant;
-import org.apache.qpid.server.handler.ExchangeBoundHandler;
import org.apache.qpid.url.AMQBindingURL;
import org.apache.qpid.url.URLSyntaxException;
+import java.io.Serializable;
+import java.text.MessageFormat;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+
public class AMQSession extends Closeable implements Session, QueueSession, TopicSession
{
private static final Logger _logger = Logger.getLogger(AMQSession.class);
@@ -115,6 +113,10 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
private int _defaultPrefetchHighMark = DEFAULT_PREFETCH_HIGH_MARK;
private int _defaultPrefetchLowMark = DEFAULT_PREFETCH_LOW_MARK;
+ private MessageListener _messageListener = null;
+
+ private AtomicBoolean _startedAtLeastOnce = new AtomicBoolean(false);
+
/**
* Used to reference durable subscribers so they requests for unsubscribe can be handled
* correctly. Note this only keeps a record of subscriptions which have been created
@@ -137,8 +139,11 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
*/
private final FlowControllingBlockingQueue _queue;
+ // working
private ConcurrentLinkedQueue<Long> _unacknowledged = new ConcurrentLinkedQueue();
-
+ // merge-right.r501854
+ private final java.util.Queue<MessageConsumerPair> _reprocessQueue;
+
private Dispatcher _dispatcher;
private MessageFactoryRegistry _messageFactoryRegistry;
@@ -151,7 +156,7 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
/**
* Maps from consumer tag (String) to JMSMessageConsumer instance
*/
- private Map<String, BasicMessageConsumer> _consumers = new ConcurrentHashMap<String, BasicMessageConsumer>();
+ private Map<AMQShortString, BasicMessageConsumer> _consumers = new ConcurrentHashMap<AMQShortString, BasicMessageConsumer>();
/**
* Maps from destination to count of JMSMessageConsumers
@@ -186,16 +191,27 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
private volatile AtomicBoolean _stopped = new AtomicBoolean(true);
/**
+ * Used to signal 'pausing' the dispatcher when setting a message listener on a consumer
+ */
+ private final AtomicBoolean _pausingDispatcher = new AtomicBoolean(false);
+
+ /**
+ * Used to signal 'pausing' the dispatcher when setting a message listener on a consumer
+ */
+ private final AtomicBoolean _pausedDispatcher = new AtomicBoolean(false);
+
+ /**
* Set when recover is called. This is to handle the case where recover() is called by application code
* during onMessage() processing. We need to make sure we do not send an auto ack if recover was called.
*/
private boolean _inRecovery;
-
+ private boolean _hasMessageListeners;
/**
* Responsible for decoding a message fragment and passing it to the appropriate message consumer.
*/
+
private class Dispatcher extends Thread
{
public Dispatcher()
@@ -224,57 +240,18 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
private void dispatchMessage(UnprocessedMessage message)
{
- if (message.contents != null)
- {
- final BasicMessageConsumer consumer = (BasicMessageConsumer) _consumers.get(message.contentHeader.getDestination());
+ final BasicMessageConsumer consumer = (BasicMessageConsumer) _consumers.get(message.getMessageHeaders().getDestination());
- if (consumer == null)
- {
- _logger.warn("Received a message from queue " + message.contentHeader.getDestination() + " without a handler - ignoring...");
- _logger.warn("Consumers that exist: " + _consumers);
- _logger.warn("Session hashcode: " + System.identityHashCode(this));
- }
- else
- {
-
- consumer.notifyMessage(message, _channelId);
-
- }
+ if (consumer == null)
+ {
+ _logger.warn("Received a message from queue " + message.getMessageHeaders().getDestination() + " without a handler - ignoring...");
+ _logger.warn("Consumers that exist: " + _consumers);
+ _logger.warn("Session hashcode: " + System.identityHashCode(this));
}
- /*else
+ else
{
- try
- {
- // Bounced message is processed here, away from the mina thread
- AbstractJMSMessage bouncedMessage = _messageFactoryRegistry.createMessage(0,
- false,
- message.contentHeader,
- message.content);
-
- int errorCode = message.bounceBody.replyCode;
- String reason = message.bounceBody.replyText;
- _logger.debug("Message returned with error code " + errorCode + " (" + reason + ")");
-
- //@TODO should this be moved to an exception handler of sorts. Somewhere errors are converted to correct execeptions.
- if (errorCode == AMQConstant.NO_CONSUMERS.getCode())
- {
- _connection.exceptionReceived(new AMQNoConsumersException("Error: " + reason, bouncedMessage));
- }
- else if (errorCode == AMQConstant.NO_ROUTE.getCode())
- {
- _connection.exceptionReceived(new AMQNoRouteException("Error: " + reason, bouncedMessage));
- }
- else
- {
- _connection.exceptionReceived(new AMQUndeliveredException(errorCode, "Error: " + reason, bouncedMessage));
- }
-
- }
- catch (Exception e)
- {
- _logger.error("Caught exception trying to raise undelivered message exception (dump follows) - ignoring...", e);
- }
- }*/
+ consumer.notifyMessage(message, _channelId);
+ }
}
public void stopDispatcher()
@@ -284,6 +261,8 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
}
}
+
+
AMQSession(AMQConnection con, int channelId, boolean transacted, int acknowledgeMode,
MessageFactoryRegistry messageFactoryRegistry)
{
@@ -314,6 +293,8 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
_defaultPrefetchHighMark = defaultPrefetchHighMark;
_defaultPrefetchLowMark = defaultPrefetchLowMark;
+ _reprocessQueue = new ConcurrentLinkedQueue<MessageConsumerPair>();
+
if (_acknowledgeMode == NO_ACKNOWLEDGE)
{
_queue = new FlowControllingBlockingQueue(_defaultPrefetchHighMark, _defaultPrefetchLowMark,
@@ -374,136 +355,69 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
public BytesMessage createBytesMessage() throws JMSException
{
- synchronized(_connection.getFailoverMutex())
+ synchronized (_connection.getFailoverMutex())
{
checkNotClosed();
- try
- {
- return (BytesMessage) _messageFactoryRegistry.createMessage("application/octet-stream");
- }
- catch (AMQException e)
- {
- throw new JMSException("Unable to create message: " + e);
- }
+ return new JMSBytesMessage();
}
}
public MapMessage createMapMessage() throws JMSException
{
- synchronized(_connection.getFailoverMutex())
+ synchronized (_connection.getFailoverMutex())
{
checkNotClosed();
- try
- {
- return (MapMessage) _messageFactoryRegistry.createMessage("jms/map-message");
- }
- catch (AMQException e)
- {
- throw new JMSException("Unable to create message: " + e);
- }
+ return new JMSMapMessage();
}
}
public javax.jms.Message createMessage() throws JMSException
{
- synchronized(_connection.getFailoverMutex())
- {
- checkNotClosed();
- try
- {
- return (BytesMessage) _messageFactoryRegistry.createMessage("application/octet-stream");
- }
- catch (AMQException e)
- {
- throw new JMSException("Unable to create message: " + e);
- }
- }
+ return createBytesMessage();
}
public ObjectMessage createObjectMessage() throws JMSException
{
- synchronized(_connection.getFailoverMutex())
+ synchronized (_connection.getFailoverMutex())
{
checkNotClosed();
- try
- {
- return (ObjectMessage) _messageFactoryRegistry.createMessage("application/java-object-stream");
- }
- catch (AMQException e)
- {
- throw new JMSException("Unable to create message: " + e);
- }
+ return (ObjectMessage) new JMSObjectMessage();
}
}
public ObjectMessage createObjectMessage(Serializable object) throws JMSException
{
- synchronized(_connection.getFailoverMutex())
- {
- checkNotClosed();
- try
- {
- ObjectMessage msg = (ObjectMessage) _messageFactoryRegistry.createMessage("application/java-object-stream");
- msg.setObject(object);
- return msg;
- }
- catch (AMQException e)
- {
- throw new JMSException("Unable to create message: " + e);
- }
- }
+ ObjectMessage msg = createObjectMessage();
+ msg.setObject(object);
+ return msg;
}
public StreamMessage createStreamMessage() throws JMSException
{
- synchronized(_connection.getFailoverMutex())
+ synchronized (_connection.getFailoverMutex())
{
checkNotClosed();
- try
- {
- return (StreamMessage) _messageFactoryRegistry.createMessage(JMSStreamMessage.MIME_TYPE);
- }
- catch (AMQException e)
- {
- throw new JMSException("Unable to create text message: " + e);
- }
+ return new JMSStreamMessage();
}
}
public TextMessage createTextMessage() throws JMSException
{
- synchronized(_connection.getFailoverMutex())
+ synchronized (_connection.getFailoverMutex())
{
checkNotClosed();
- try
- {
- return (TextMessage) _messageFactoryRegistry.createMessage("text/plain");
- }
- catch (AMQException e)
- {
- throw new JMSException("Unable to create text message: " + e);
- }
+ return new JMSTextMessage();
}
}
public TextMessage createTextMessage(String text) throws JMSException
{
- synchronized(_connection.getFailoverMutex())
- {
- checkNotClosed();
- try
- {
- TextMessage msg = (TextMessage) _messageFactoryRegistry.createMessage("text/plain");
- msg.setText(text);
- return msg;
- }
- catch (AMQException e)
- {
- throw new JMSException("Unable to create text message: " + e);
- }
- }
+
+ TextMessage msg = createTextMessage();
+ msg.setText(text);
+ return msg;
}
public boolean getTransacted() throws JMSException
@@ -532,10 +446,11 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
}
// Commits outstanding messages sent and outstanding acknowledgements.
- // AMQP version change: Hardwire the version to 0-9 (major=0, minor=9)
- // TODO: Connect this to the session version obtained from ProtocolInitiation for this session.
// Be aware of possible changes to parameter order as versions change.
- _connection.getProtocolHandler().syncWrite(_channelId, TxCommitBody.createMethodBody((byte)0, (byte)9), TxCommitOkBody.class);
+ _connection.getProtocolHandler().syncWrite(_channelId, TxCommitBody.createMethodBody(
+ getProtocolMajorVersion(),
+ getProtocolMinorVersion()),
+ TxCommitOkBody.class);
}
catch (AMQException e)
{
@@ -545,17 +460,18 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
}
}
+
public void rollback() throws JMSException
{
checkTransacted();
try
{
_unacknowledged.clear();
- // AMQP version change: Hardwire the version to 0-9 (major=0, minor=9)
- // TODO: Connect this to the session version obtained from ProtocolInitiation for this session.
// Be aware of possible changes to parameter order as versions change.
- _connection.getProtocolHandler().syncWrite(_channelId,
- TxRollbackBody.createMethodBody((byte)0, (byte)9), TxRollbackOkBody.class);
+ _connection.getProtocolHandler().syncWrite(_channelId, TxRollbackBody.createMethodBody(
+ getProtocolMajorVersion(),
+ getProtocolMinorVersion()),
+ TxRollbackOkBody.class);
}
catch (AMQException e)
{
@@ -565,9 +481,14 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
public void close() throws JMSException
{
+ close(-1);
+ }
+
+ public void close(long timeout) throws JMSException
+ {
// We must close down all producers and consumers in an orderly fashion. This is the only method
// that can be called from a different thread of control from the one controlling the session
- synchronized(_connection.getFailoverMutex())
+ synchronized (_connection.getFailoverMutex())
{
//Ensure we only try and close an open session.
if (!_closed.getAndSet(true))
@@ -578,15 +499,14 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
try
{
_connection.getProtocolHandler().closeSession(this);
- // AMQP version change: Hardwire the version to 0-9 (major=0, minor=9)
- // TODO: Connect this to the session version obtained from ProtocolInitiation for this session.
// Be aware of possible changes to parameter order as versions change.
final AMQMethodBody methodBody = ChannelCloseBody.createMethodBody(
- (byte)0, (byte)9, // AMQP version (major, minor)
+ getProtocolMajorVersion(),
+ getProtocolMinorVersion(),
0, // classId
0, // methodId
AMQConstant.REPLY_SUCCESS.getCode(), // replyCode
- "JMS client closing channel"); // replyText
+ new AMQShortString("JMS client closing channel")); // replyText
_connection.getProtocolHandler().syncWrite(getChannelId(), methodBody, ChannelCloseOkBody.class);
// When control resumes at this point, a reply will have been received that
// indicates the broker has closed the channel successfully
@@ -606,13 +526,31 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
}
}
+ private AMQProtocolHandler getProtocolHandler()
+ {
+ return _connection.getProtocolHandler();
+ }
+
+
+ private byte getProtocolMinorVersion()
+ {
+ return getProtocolHandler().getProtocolMinorVersion();
+ }
+
+ private byte getProtocolMajorVersion()
+ {
+ return getProtocolHandler().getProtocolMajorVersion();
+ }
+
+
/**
* Close all producers or consumers. This is called either in the error case or when closing the session normally.
*
* @param amqe the exception, may be null to indicate no error has occurred
*/
- private void closeProducersAndConsumers(AMQException amqe)
+ private void closeProducersAndConsumers(AMQException amqe) throws JMSException
{
+ JMSException jmse = null;
try
{
closeProducers();
@@ -620,6 +558,7 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
catch (JMSException e)
{
_logger.error("Error closing session: " + e, e);
+ jmse = e;
}
try
{
@@ -628,7 +567,19 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
catch (JMSException e)
{
_logger.error("Error closing session: " + e, e);
+ if (jmse == null)
+ {
+ jmse = e;
+ }
+ }
+ finally
+ {
+ if (jmse != null)
+ {
+ throw jmse;
+ }
}
+
}
/**
@@ -637,9 +588,9 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
*
* @param e the exception that caused this session to be closed. Null causes the
*/
- public void closed(Throwable e)
+ public void closed(Throwable e) throws JMSException
{
- synchronized(_connection.getFailoverMutex())
+ synchronized (_connection.getFailoverMutex())
{
// An AMQException has an error code and message already and will be passed in when closure occurs as a
// result of a channel close request
@@ -777,14 +728,17 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
consumer.clearUnackedMessages();
}
_unacknowledged.clear();
- // AMQP version change: Hardwire the version to 0-9 (major=0, minor=9)
- // TODO: Connect this to the session version obtained from ProtocolInitiation for this session.
// Be aware of possible changes to parameter order as versions change.
- try {
+ try
+ {
_connection.getProtocolHandler().writeRequest(_channelId,
- MessageRecoverBody.createMethodBody((byte)0, (byte)9, // AMQP version (major, minor)
+ MessageRecoverBody.createMethodBody(
+ getProtocolMajorVersion(),
+ getProtocolMinorVersion(),
false)); // requeue
- } catch (AMQException e) {
+ }
+ catch (AMQException e)
+ {
_logger.error("Error recovering",e);
JMSException ex = new JMSException("Error Recovering");
ex.initCause(e);
@@ -820,13 +774,37 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
public MessageListener getMessageListener() throws JMSException
{
checkNotClosed();
- throw new java.lang.UnsupportedOperationException("MessageListener interface not supported");
+ return _messageListener;
}
public void setMessageListener(MessageListener listener) throws JMSException
{
checkNotClosed();
- throw new java.lang.UnsupportedOperationException("MessageListener interface not supported");
+
+ if (!isStopped())
+ {
+ throw new javax.jms.IllegalStateException("Attempt to set listener while session is started.");
+ }
+
+ // We are stopped
+ for (Iterator<BasicMessageConsumer> i = _consumers.values().iterator(); i.hasNext();)
+ {
+ BasicMessageConsumer consumer = i.next();
+
+ if (consumer.isReceiving())
+ {
+ throw new javax.jms.IllegalStateException("Another thread is already receiving synchronously.");
+ }
+ }
+
+ _messageListener = listener;
+
+ for (Iterator<BasicMessageConsumer> i = _consumers.values().iterator(); i.hasNext();)
+ {
+ i.next().setMessageListener(_messageListener);
+ }
+
+
}
public void run()
@@ -858,6 +836,12 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
return createProducerImpl(destination, DEFAULT_MANDATORY, DEFAULT_IMMEDIATE);
}
+ // Test purposes only - used for testing refs, which cannot be done using JMS interfaces
+ public BasicMessageProducer createBasicProducer(Topic destination) throws JMSException
+ {
+ return (BasicMessageProducer)createProducerImpl(destination, DEFAULT_MANDATORY, DEFAULT_IMMEDIATE);
+ }
+
private org.apache.qpid.jms.MessageProducer createProducerImpl(Destination destination, boolean mandatory,
boolean immediate)
throws JMSException
@@ -883,7 +867,10 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
registerProducer(producerId, producer);
return producer;
}
- catch (AMQException e) { throw new JMSException(e.toString()); }
+ catch (AMQException e)
+ {
+ throw new JMSException(e.toString());
+ }
}
}.execute(_connection);
}
@@ -964,8 +951,8 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
}
public MessageConsumer createBrowserConsumer(Destination destination,
- String messageSelector,
- boolean noLocal)
+ String messageSelector,
+ boolean noLocal)
throws JMSException
{
checkValidDestination(destination);
@@ -1039,6 +1026,7 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
{
checkTemporaryDestination(destination);
+
return (org.apache.qpid.jms.MessageConsumer) new FailoverSupport()
{
public Object operation() throws JMSException
@@ -1047,7 +1035,7 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
AMQDestination amqd = (AMQDestination) destination;
- final AMQProtocolHandler protocolHandler = _connection.getProtocolHandler();
+ final AMQProtocolHandler protocolHandler = getProtocolHandler();
// TODO: construct the rawSelector from the selector string if rawSelector == null
final FieldTable ft = FieldTableFactory.newFieldTable();
//if (rawSelector != null)
@@ -1061,6 +1049,11 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
protocolHandler, ft, prefetchHigh, prefetchLow, exclusive,
_acknowledgeMode, noConsume, autoClose);
+ if (_messageListener != null)
+ {
+ consumer.setMessageListener(_messageListener);
+ }
+
try
{
registerConsumer(consumer, false);
@@ -1074,11 +1067,14 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
catch (AMQException e)
{
JMSException ex = new JMSException("Error registering consumer: " + e);
+
+ //todo remove
+ e.printStackTrace();
ex.setLinkedException(e);
throw ex;
}
- synchronized(destination)
+ synchronized (destination)
{
_destinationConsumerCount.putIfAbsent(destination, new AtomicInteger());
_destinationConsumerCount.get(destination).incrementAndGet();
@@ -1118,18 +1114,17 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
}
- public void declareExchange(String name, String type) throws AMQException
+ public void declareExchange(AMQShortString name, AMQShortString type) throws AMQException
{
- declareExchange(name, type, _connection.getProtocolHandler());
+ declareExchange(name, type, getProtocolHandler());
}
- public void declareExchangeSynch(String name, String type) throws AMQException
+ public void declareExchangeSynch(AMQShortString name, AMQShortString type) throws AMQException
{
- // AMQP version change: Hardwire the version to 0-9 (major=0, minor=9)
- // TODO: Connect this to the session version obtained from ProtocolInitiation for this session.
// Be aware of possible changes to parameter order as versions change.
AMQMethodBody methodBody = ExchangeDeclareBody.createMethodBody(
- (byte)0, (byte)9, // AMQP version (major, minor)
+ getProtocolMajorVersion(), // AMQP major version
+ getProtocolMinorVersion(), // AMQP minor version
null, // arguments
false, // autoDelete
false, // durable
@@ -1142,18 +1137,17 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
_connection.getProtocolHandler().syncWrite(_channelId, methodBody, ExchangeDeclareOkBody.class);
}
- private void declareExchange(AMQDestination amqd, AMQProtocolHandler protocolHandler)throws AMQException
+ private void declareExchange(AMQDestination amqd, AMQProtocolHandler protocolHandler) throws AMQException
{
declareExchange(amqd.getExchangeName(), amqd.getExchangeClass(), protocolHandler);
}
- private void declareExchange(String name, String type, AMQProtocolHandler protocolHandler) throws AMQException
+ private void declareExchange(AMQShortString name, AMQShortString type, AMQProtocolHandler protocolHandler) throws AMQException
{
- // AMQP version change: Hardwire the version to 0-9 (major=0, minor=9)
- // TODO: Connect this to the session version obtained from ProtocolInitiation for this session.
// Be aware of possible changes to parameter order as versions change.
AMQMethodBody methodBody = ExchangeDeclareBody.createMethodBody(
- (byte)0, (byte)9, // AMQP version (major, minor)
+ getProtocolMajorVersion(), // AMQP major version
+ getProtocolMinorVersion(), // AMQP minor version
null, // arguments
false, // autoDelete
false, // durable
@@ -1175,7 +1169,7 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
* @return the queue name. This is useful where the broker is generating a queue name on behalf of the client.
* @throws AMQException
*/
- private String declareQueue(AMQDestination amqd, AMQProtocolHandler protocolHandler) throws AMQException
+ private AMQShortString declareQueue(AMQDestination amqd, AMQProtocolHandler protocolHandler) throws AMQException
{
// For queues (but not topics) we generate the name in the client rather than the
// server. This allows the name to be reused on failover if required. In general,
@@ -1185,38 +1179,35 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
amqd.setQueueName(protocolHandler.generateQueueName());
}
- // AMQP version change: Hardwire the version to 0-9 (major=0, minor=9)
- // TODO: Connect this to the session version obtained from ProtocolInitiation for this session.
// Be aware of possible changes to parameter order as versions change.
AMQMethodBody methodBody = QueueDeclareBody.createMethodBody(
- (byte)0, (byte)9, // AMQP version (major, minor)
+ getProtocolMajorVersion(), // AMQP major version
+ getProtocolMinorVersion(), // AMQP minor version
null, // arguments
amqd.isAutoDelete(), // autoDelete
amqd.isDurable(), // durable
amqd.isExclusive(), // exclusive
true, // nowait
false, // passive
- amqd.getQueueName(), // queue
+ amqd.getAMQQueueName(), // queue
0); // ticket
protocolHandler.writeRequest(_channelId, methodBody);
- return amqd.getQueueName();
+ return amqd.getAMQQueueName();
}
- private void bindQueue(AMQDestination amqd, String queueName, AMQProtocolHandler protocolHandler, FieldTable ft) throws AMQException
+ private void bindQueue(AMQDestination amqd, AMQShortString queueName, AMQProtocolHandler protocolHandler, FieldTable ft) throws AMQException
{
- // AMQP version change: Hardwire the version to 0-9 (major=0, minor=9)
- // TODO: Connect this to the session version obtained from ProtocolInitiation for this session.
// Be aware of possible changes to parameter order as versions change.
AMQMethodBody methodBody = QueueBindBody.createMethodBody(
- (byte)0, (byte)9, // AMQP version (major, minor)
+ getProtocolMajorVersion(), // AMQP major version
+ getProtocolMinorVersion(), // AMQP minor version
ft, // arguments
amqd.getExchangeName(), // exchange
true, // nowait
queueName, // queue
amqd.getRoutingKey(), // routingKey
0); // ticket
-
protocolHandler.writeRequest(_channelId, methodBody);
}
@@ -1226,23 +1217,23 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
* @param queueName
* @return the consumer tag generated by the broker
*/
- private void consumeFromQueue(BasicMessageConsumer consumer, String queueName, AMQProtocolHandler protocolHandler,
+ private void consumeFromQueue(BasicMessageConsumer consumer, AMQShortString queueName, AMQProtocolHandler protocolHandler,
boolean nowait, String messageSelector) throws AMQException
{
//fixme prefetch values are not used here. Do we need to have them as parametsrs?
//need to generate a consumer tag on the client so we can exploit the nowait flag
- String tag = Integer.toString(_nextTag++);
+ AMQShortString tag = new AMQShortString(Integer.toString(_nextTag++));
FieldTable arguments = FieldTableFactory.newFieldTable();
if (messageSelector != null && !messageSelector.equals(""))
{
arguments.put(AMQPFilterTypes.JMS_SELECTOR.getValue(), messageSelector);
}
- if(consumer.isAutoClose())
+ if (consumer.isAutoClose())
{
arguments.put(AMQPFilterTypes.AUTO_CLOSE.getValue(), Boolean.TRUE);
}
- if(consumer.isNoConsume())
+ if (consumer.isNoConsume())
{
arguments.put(AMQPFilterTypes.NO_CONSUME.getValue(), Boolean.TRUE);
}
@@ -1253,29 +1244,17 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
try
{
- // AMQP version change: Hardwire the version to 0-9 (major=0, minor=9)
- // TODO: Connect this to the session version obtained from ProtocolInitiation for this session.
// Be aware of possible changes to parameter order as versions change.
- /*AMQFrame jmsConsume = BasicConsumeBody.createAMQFrame(_channelId,
- (byte)0, (byte)9, // AMQP version (major, minor)
- arguments, // arguments
- tag, // consumerTag
- consumer.isExclusive(), // exclusive
- consumer.getAcknowledgeMode() == Session.NO_ACKNOWLEDGE, // noAck
- consumer.isNoLocal(), // noLocal
- nowait, // nowait
- queueName, // queue
- 0); // ticket */
-
AMQMethodBody methodBody = MessageConsumeBody.createMethodBody(
- (byte)0, (byte)9, // AMQP version (major, minor)
- tag, // consumerTag
- consumer.isExclusive(), // exclusive
- arguments, // arguments in the form of a field table
- consumer.getAcknowledgeMode() == Session.NO_ACKNOWLEDGE, // noAck
- consumer.isNoLocal(), // noLocal
- queueName, // queue
- 0); // ticket */
+ getProtocolMajorVersion(), // AMQP major version
+ getProtocolMinorVersion(), // AMQP minor version
+ tag, // consumerTag
+ consumer.isExclusive(), // exclusive
+ arguments, // arguments in the form of a field table
+ consumer.getAcknowledgeMode() == Session.NO_ACKNOWLEDGE, // noAck
+ consumer.isNoLocal(), // noLocal
+ queueName, // queue
+ 0); // ticket */
/*
if (nowait)
{
@@ -1364,7 +1343,7 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
if (topicName.indexOf('/') == -1)
{
- return new AMQTopic(topicName);
+ return new AMQTopic(new AMQShortString(topicName));
}
else
{
@@ -1434,12 +1413,21 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
}
else
{
+ AMQShortString topicName;
+ if (topic instanceof AMQTopic)
+ {
+ topicName = ((AMQTopic) topic).getDestinationName();
+ }
+ else
+ {
+ topicName = new AMQShortString(topic.getTopicName());
+ }
// if the queue is bound to the exchange but NOT for this topic, then the JMS spec
// says we must trash the subscription.
- if (isQueueBound(dest.getQueueName()) &&
- !isQueueBound(dest.getQueueName(), topic.getTopicName()))
+ if (isQueueBound(dest.getAMQQueueName()) &&
+ !isQueueBound(dest.getAMQQueueName(), topicName))
{
- deleteQueue(dest.getQueueName());
+ deleteQueue(dest.getAMQQueueName());
}
}
@@ -1451,15 +1439,14 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
return subscriber;
}
- void deleteQueue(String queueName) throws JMSException
+ void deleteQueue(AMQShortString queueName) throws JMSException
{
try
{
- // AMQP version change: Hardwire the version to 0-9 (major=0, minor=9)
- // TODO: Connect this to the session version obtained from ProtocolInitiation for this session.
// Be aware of possible changes to parameter order as versions change.
AMQMethodBody methodBody = QueueDeleteBody.createMethodBody(
- (byte)0, (byte)9, // AMQP version (major, minor)
+ getProtocolMajorVersion(), // AMQP major version
+ getProtocolMinorVersion(), // AMQP minor version
false, // ifEmpty
false, // ifUnused
true, // nowait
@@ -1504,7 +1491,7 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
{
checkNotClosed();
checkValidQueue(queue);
- return new AMQQueueBrowser(this, (AMQQueue) queue,messageSelector);
+ return new AMQQueueBrowser(this, (AMQQueue) queue, messageSelector);
}
public TemporaryQueue createTemporaryQueue() throws JMSException
@@ -1543,18 +1530,17 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
}
}
- boolean isQueueBound(String queueName) throws JMSException
+ boolean isQueueBound(AMQShortString queueName) throws JMSException
{
return isQueueBound(queueName, null);
}
- boolean isQueueBound(String queueName, String routingKey) throws JMSException
+ boolean isQueueBound(AMQShortString queueName, AMQShortString routingKey) throws JMSException
{
- // AMQP version change: Hardwire the version to 0-9 (major=0, minor=9)
- // TODO: Connect this to the session version obtained from ProtocolInitiation for this session.
// Be aware of possible changes to parameter order as versions change.
AMQMethodBody methodBody = ExchangeBoundBody.createMethodBody(
- (byte)0, (byte)9, // AMQP version (major, minor)
+ getProtocolMajorVersion(), // AMQP major version
+ getProtocolMinorVersion(), // AMQP minor version
ExchangeDefaults.TOPIC_EXCHANGE_NAME, // exchange
queueName, // queue
routingKey); // routingKey
@@ -1568,7 +1554,7 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
throw new JMSAMQException(e);
}
ExchangeBoundOkBody responseBody = (ExchangeBoundOkBody) response.getMethod();
- return (responseBody.replyCode == ExchangeBoundHandler.OK);
+ return (responseBody.replyCode == 0); //ExchangeBoundHandler.OK); Remove Broker compile dependency
}
private void checkTransacted() throws JMSException
@@ -1600,7 +1586,7 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
_logger.debug("Message received in session with channel id " + _channelId);
}
- _unacknowledged.offer(message.deliveryTag);
+ _unacknowledged.offer(message.getDeliveryTag());
_queue.add(message);
}
@@ -1616,10 +1602,8 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
*/
public synchronized void acknowledgeMessage(long requestId, boolean multiple) throws AMQException
{
- // AMQP version change: Hardwire the version to 0-9 (major=0, minor=9)
- // TODO: Connect this to the session version obtained from ProtocolInitiation for this session.
// Be aware of possible changes to parameter order as versions change.
- final AMQMethodBody methodBody = MessageOkBody.createMethodBody((byte)0, (byte)9); // AMQP version (major, minor)
+ final AMQMethodBody methodBody = MessageOkBody.createMethodBody(getProtocolMajorVersion(), getProtocolMinorVersion()); // AMQP version (major, minor)
if (_logger.isDebugEnabled())
{
_logger.debug("Sending ack for request ID " + requestId + " on channel " + _channelId);
@@ -1659,7 +1643,7 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
void start()
{
- if (_dispatcher != null)
+ if (_startedAtLeastOnce.getAndSet(true))
{
try{
//then we stopped this and are restarting, so signal server to resume delivery
@@ -1668,9 +1652,31 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
_logger.error("Error Un Suspending Channel", e);
}
}
- _dispatcher = new Dispatcher();
- _dispatcher.setDaemon(true);
- _dispatcher.start();
+
+ if(hasMessageListeners() && _dispatcher == null)
+ {
+ startDistpatcherIfNecessary();
+ }
+ }
+
+ private boolean hasMessageListeners()
+ {
+ return _hasMessageListeners;
+ }
+
+ void setHasMessageListeners()
+ {
+ _hasMessageListeners = true;
+ }
+
+ synchronized void startDistpatcherIfNecessary()
+ {
+ if(_dispatcher == null)
+ {
+ _dispatcher = new Dispatcher();
+ _dispatcher.setDaemon(true);
+ _dispatcher.start();
+ }
}
void stop()
@@ -1682,7 +1688,7 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
_logger.error("Error Suspending Channel", e);
}
-//stop the dispatcher thread
+ //stop the dispatcher thread
_stopped.set(true);
}
@@ -1701,11 +1707,11 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
{
AMQDestination amqd = consumer.getDestination();
- AMQProtocolHandler protocolHandler = _connection.getProtocolHandler();
+ AMQProtocolHandler protocolHandler = getProtocolHandler();
declareExchange(amqd, protocolHandler);
- String queueName = declareQueue(amqd, protocolHandler);
+ AMQShortString queueName = declareQueue(amqd, protocolHandler);
bindQueue(amqd, queueName, protocolHandler, consumer.getRawSelectorFieldTable());
@@ -1727,19 +1733,21 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
*/
void deregisterConsumer(BasicMessageConsumer consumer)
{
- _consumers.remove(consumer.getConsumerTag());
- String subscriptionName = _reverseSubscriptionMap.remove(consumer);
- if (subscriptionName != null)
+ if (_consumers.remove(consumer.getConsumerTag()) != null)
{
- _subscriptions.remove(subscriptionName);
- }
+ String subscriptionName = _reverseSubscriptionMap.remove(consumer);
+ if (subscriptionName != null)
+ {
+ _subscriptions.remove(subscriptionName);
+ }
- Destination dest = consumer.getDestination();
- synchronized(dest)
- {
- if (_destinationConsumerCount.get(dest).decrementAndGet() == 0)
+ Destination dest = consumer.getDestination();
+ synchronized (dest)
{
- _destinationConsumerCount.remove(dest);
+ if (_destinationConsumerCount.get(dest).decrementAndGet() == 0)
+ {
+ _destinationConsumerCount.remove(dest);
+ }
}
}
}
@@ -1773,7 +1781,7 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
private void resubscribeProducers() throws AMQException
{
ArrayList producers = new ArrayList(_producers.values());
- _logger.info(MessageFormat.format("Resubscribing producers = {0} producers.size={1}", producers, producers.size())); // FIXME: remove
+ _logger.info(MessageFormat.format("Resubscribing producers = {0} producers.size={1}", producers, producers.size())); // FIXME: removeKey
for (Iterator it = producers.iterator(); it.hasNext();)
{
BasicMessageProducer producer = (BasicMessageProducer) it.next();
@@ -1796,11 +1804,10 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
private void suspendChannel() throws AMQException
{
_logger.warn("Suspending channel");
- // AMQP version change: Hardwire the version to 0-9 (major=0, minor=9)
- // TODO: Connect this to the session version obtained from ProtocolInitiation for this session.
// Be aware of possible changes to parameter order as versions change.
AMQMethodBody methodBody = ChannelFlowBody.createMethodBody(
- (byte)0, (byte)9, // AMQP version (major, minor)
+ getProtocolMajorVersion(), // AMQP major version
+ getProtocolMinorVersion(), // AMQP minor version
false); // active
_connection.getProtocolHandler().writeRequest(_channelId, methodBody);
}
@@ -1808,19 +1815,18 @@ public class AMQSession extends Closeable implements Session, QueueSession, Topi
private void unsuspendChannel() throws AMQException
{
_logger.warn("Unsuspending channel");
- // AMQP version change: Hardwire the version to 0-9 (major=0, minor=9)
- // TODO: Connect this to the session version obtained from ProtocolInitiation for this session.
// Be aware of possible changes to parameter order as versions change.
AMQMethodBody methodBody = ChannelFlowBody.createMethodBody(
- (byte)0, (byte)9, // AMQP version (major, minor)
+ getProtocolMajorVersion(), // AMQP major version
+ getProtocolMinorVersion(), // AMQP minor version
true); // active
_connection.getProtocolHandler().writeRequest(_channelId, methodBody);
}
- public void confirmConsumerCancelled(String consumerTag)
+ public void confirmConsumerCancelled(AMQShortString consumerTag)
{
BasicMessageConsumer consumer = (BasicMessageConsumer) _consumers.get(consumerTag);
- if((consumer != null) && (consumer.isAutoClose()))
+ if ((consumer != null) && (consumer.isAutoClose()))
{
consumer.closeWhenNoMessages(true);
}
diff --git a/java/client/src/main/java/org/apache/qpid/client/AMQTemporaryQueue.java b/java/client/src/main/java/org/apache/qpid/client/AMQTemporaryQueue.java
index 81fee69f90..18c655a829 100644
--- a/java/client/src/main/java/org/apache/qpid/client/AMQTemporaryQueue.java
+++ b/java/client/src/main/java/org/apache/qpid/client/AMQTemporaryQueue.java
@@ -20,6 +20,8 @@
*/
package org.apache.qpid.client;
+import org.apache.qpid.framing.AMQShortString;
+
import javax.jms.JMSException;
import javax.jms.TemporaryQueue;
@@ -38,7 +40,7 @@ final class AMQTemporaryQueue extends AMQQueue implements TemporaryQueue, Tempor
*/
public AMQTemporaryQueue(AMQSession session)
{
- super("TempQueue" + Long.toString(System.currentTimeMillis()), true);
+ super(new AMQShortString("TempQueue" + Long.toString(System.currentTimeMillis())), true);
_session = session;
}
diff --git a/java/client/src/main/java/org/apache/qpid/client/AMQTopic.java b/java/client/src/main/java/org/apache/qpid/client/AMQTopic.java
index 39304f3f4c..f50b0390c5 100644
--- a/java/client/src/main/java/org/apache/qpid/client/AMQTopic.java
+++ b/java/client/src/main/java/org/apache/qpid/client/AMQTopic.java
@@ -22,6 +22,7 @@ package org.apache.qpid.client;
import org.apache.qpid.url.BindingURL;
import org.apache.qpid.exchange.ExchangeDefaults;
+import org.apache.qpid.framing.AMQShortString;
import javax.jms.JMSException;
import javax.jms.Topic;
@@ -40,10 +41,21 @@ public class AMQTopic extends AMQDestination implements Topic
public AMQTopic(String name)
{
+ this(new AMQShortString(name));
+ }
+
+ public AMQTopic(AMQShortString exchange, AMQShortString routingKey, AMQShortString queueName)
+ {
+ super(exchange, ExchangeDefaults.TOPIC_EXCHANGE_CLASS, routingKey, true, true, queueName, false);
+ }
+
+
+ public AMQTopic(AMQShortString name)
+ {
this(name, true, null, false);
}
- public AMQTopic(String name, boolean isAutoDelete, String queueName, boolean isDurable)
+ public AMQTopic(AMQShortString name, boolean isAutoDelete, AMQShortString queueName, boolean isDurable)
{
super(ExchangeDefaults.TOPIC_EXCHANGE_NAME, ExchangeDefaults.TOPIC_EXCHANGE_CLASS, name, true, isAutoDelete,
queueName, isDurable);
@@ -56,17 +68,17 @@ public class AMQTopic extends AMQDestination implements Topic
true);
}
- public static String getDurableTopicQueueName(String subscriptionName, AMQConnection connection) throws JMSException
+ public static AMQShortString getDurableTopicQueueName(String subscriptionName, AMQConnection connection) throws JMSException
{
- return connection.getClientID() + ":" + subscriptionName;
+ return new AMQShortString(connection.getClientID() + ":" + subscriptionName);
}
public String getTopicName() throws JMSException
{
- return super.getDestinationName();
+ return super.getDestinationName().toString();
}
- public String getRoutingKey()
+ public AMQShortString getRoutingKey()
{
return getDestinationName();
}
diff --git a/java/client/src/main/java/org/apache/qpid/client/AMQUndefinedDestination.java b/java/client/src/main/java/org/apache/qpid/client/AMQUndefinedDestination.java
new file mode 100644
index 0000000000..0f3723c58b
--- /dev/null
+++ b/java/client/src/main/java/org/apache/qpid/client/AMQUndefinedDestination.java
@@ -0,0 +1,45 @@
+/*
+ *
+ * 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.client;
+
+import org.apache.qpid.framing.AMQShortString;
+
+public class AMQUndefinedDestination extends AMQDestination
+{
+
+ private static final AMQShortString UNKNOWN_EXCHANGE_CLASS = new AMQShortString("unknown");
+
+
+ public AMQUndefinedDestination(AMQShortString exchange, AMQShortString routingKey, AMQShortString queueName)
+ {
+ super(exchange, UNKNOWN_EXCHANGE_CLASS, routingKey, queueName);
+ }
+
+ public AMQShortString getRoutingKey()
+ {
+ return getDestinationName();
+ }
+
+ public boolean isNameRequired()
+ {
+ return getAMQQueueName() == null;
+ }
+}
diff --git a/java/client/src/main/java/org/apache/qpid/client/BasicMessageConsumer.java b/java/client/src/main/java/org/apache/qpid/client/BasicMessageConsumer.java
index 47213af55c..e9c755d09c 100644
--- a/java/client/src/main/java/org/apache/qpid/client/BasicMessageConsumer.java
+++ b/java/client/src/main/java/org/apache/qpid/client/BasicMessageConsumer.java
@@ -27,11 +27,6 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
-import javax.jms.Destination;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageListener;
-
import org.apache.log4j.Logger;
import org.apache.qpid.AMQException;
import org.apache.qpid.client.message.AbstractJMSMessage;
@@ -40,6 +35,7 @@ import org.apache.qpid.client.message.UnprocessedMessage;
import org.apache.qpid.client.protocol.AMQProtocolHandler;
import org.apache.qpid.framing.AMQFrame;
import org.apache.qpid.framing.AMQMethodBody;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.framing.FieldTable;
import org.apache.qpid.framing.MessageCancelBody;
import org.apache.qpid.framing.MessageOkBody;
@@ -48,6 +44,18 @@ import org.apache.qpid.jms.Session;
import org.apache.qpid.url.AMQBindingURL;
import org.apache.qpid.url.URLSyntaxException;
+import javax.jms.Destination;
+import javax.jms.JMSException;
+import javax.jms.Message;
+import javax.jms.MessageListener;
+import java.util.Iterator;
+import java.util.Queue;
+import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+
public class BasicMessageConsumer extends Closeable implements MessageConsumer
{
private static final Logger _logger = Logger.getLogger(BasicMessageConsumer.class);
@@ -70,13 +78,13 @@ public class BasicMessageConsumer extends Closeable implements MessageConsumer
/**
* Holds an atomic reference to the listener installed.
*/
- private final AtomicReference _messageListener = new AtomicReference();
+ private final AtomicReference<MessageListener> _messageListener = new AtomicReference<MessageListener>();
/**
* The consumer tag allows us to close the consumer by sending a jmsCancel method to the
* broker
*/
- private String _consumerTag;
+ private AMQShortString _consumerTag;
/**
* We need to know the channel id when constructing frames
@@ -85,13 +93,17 @@ public class BasicMessageConsumer extends Closeable implements MessageConsumer
/**
* Used in the blocking receive methods to receive a message from
- * the Session thread. Argument true indicates we want strict FIFO semantics
+ * the Session thread.
+ * <p/>
+ * Or to notify of errors
+ * <p/>
+ * Argument true indicates we want strict FIFO semantics
*/
private final ArrayBlockingQueue _synchronousQueue;
private MessageFactoryRegistry _messageFactory;
- private AMQSession _session;
+ private final AMQSession _session;
private AMQProtocolHandler _protocolHandler;
@@ -148,8 +160,8 @@ public class BasicMessageConsumer extends Closeable implements MessageConsumer
private Thread _receivingThread;
/**
- * autoClose denotes that the consumer will automatically cancel itself when there are no more messages to receive
- * on the queue. This is used for queue browsing.
+ * autoClose denotes that the consumer will automatically cancel itself when there are no more messages to receive
+ * on the queue. This is used for queue browsing.
*/
private boolean _autoClose;
private boolean _closeWhenNoMessages;
@@ -186,14 +198,14 @@ public class BasicMessageConsumer extends Closeable implements MessageConsumer
public String getMessageSelector() throws JMSException
{
- checkPreConditions();
+ checkPreConditions();
return _messageSelector;
}
public MessageListener getMessageListener() throws JMSException
{
- checkPreConditions();
- return (MessageListener) _messageListener.get();
+ checkPreConditions();
+ return _messageListener.get();
}
public int getAcknowledgeMode()
@@ -206,9 +218,9 @@ public class BasicMessageConsumer extends Closeable implements MessageConsumer
return _messageListener.get() != null;
}
- public void setMessageListener(MessageListener messageListener) throws JMSException
+ public void setMessageListener(final MessageListener messageListener) throws JMSException
{
- checkPreConditions();
+ checkPreConditions();
//if the current listener is non-null and the session is not stopped, then
//it is an error to call this method.
@@ -223,7 +235,13 @@ public class BasicMessageConsumer extends Closeable implements MessageConsumer
if (_session.isStopped())
{
_messageListener.set(messageListener);
- _logger.debug("Message listener set for destination " + _destination);
+ _session.setHasMessageListeners();
+ _session.startDistpatcherIfNecessary();
+
+ if (_logger.isDebugEnabled())
+ {
+ _logger.debug("Session stopped : Message listener(" + messageListener + ") set for destination " + _destination);
+ }
}
else
{
@@ -235,25 +253,35 @@ public class BasicMessageConsumer extends Closeable implements MessageConsumer
{
throw new javax.jms.IllegalStateException("Attempt to alter listener while session is started.");
}
+
_logger.debug("Message listener set for destination " + _destination);
if (messageListener != null)
{
- try
+// working
+// try
+// {
+// //handle case where connection has already been started, and the dispatcher is blocked
+// //doing a put on the _synchronousQueue
+// AbstractJMSMessage jmsMsg = (AbstractJMSMessage)_synchronousQueue.poll();
+// if (jmsMsg != null)
+// {
+// preApplicationProcessing(jmsMsg);
+// messageListener.onMessage(jmsMsg);
+// postDeliver(jmsMsg);
+// }
+// }
+// catch (AMQException e)
+// {
+// throw new JMSException(e.toString());
+// }
+
+// r501854
+ synchronized (_session)
{
- //handle case where connection has already been started, and the dispatcher is blocked
- //doing a put on the _synchronousQueue
- AbstractJMSMessage jmsMsg = (AbstractJMSMessage)_synchronousQueue.poll();
- if (jmsMsg != null)
- {
- preApplicationProcessing(jmsMsg);
- messageListener.onMessage(jmsMsg);
- postDeliver(jmsMsg);
- }
- }
- catch (AMQException e)
- {
- throw new JMSException(e.toString());
+ _messageListener.set(messageListener);
+ _session.setHasMessageListeners();
+ _session.startDistpatcherIfNecessary();
}
}
}
@@ -261,21 +289,12 @@ public class BasicMessageConsumer extends Closeable implements MessageConsumer
private void preApplicationProcessing(AbstractJMSMessage jmsMsg) throws JMSException
{
- if(_session.getAcknowledgeMode() == Session.CLIENT_ACKNOWLEDGE)
+
+ if (_session.getAcknowledgeMode() == Session.CLIENT_ACKNOWLEDGE)
{
_unacknowledgedDeliveryTags.add(jmsMsg.getDeliveryTag());
- String url = jmsMsg.getStringProperty(CustomJMXProperty.JMSX_QPID_JMSDESTINATIONURL.toString());
- try
- {
- Destination dest = AMQDestination.createDestination(new AMQBindingURL(url));
- jmsMsg.setJMSDestination(dest);
- }
- catch (URLSyntaxException e)
- {
- _logger.warn("Unable to parse the supplied destination header: " + url);
- }
-
}
+
_session.setInRecovery(false);
}
@@ -328,6 +347,11 @@ public class BasicMessageConsumer extends Closeable implements MessageConsumer
return _exclusive;
}
+ public boolean isReceiving()
+ {
+ return _receiving.get();
+ }
+
public Message receive() throws JMSException
{
return receive(0);
@@ -335,13 +359,15 @@ public class BasicMessageConsumer extends Closeable implements MessageConsumer
public Message receive(long l) throws JMSException
{
- checkPreConditions();
+ _session.startDistpatcherIfNecessary();
+
+ checkPreConditions();
acquireReceiving();
try
{
- if(closeOnAutoClose())
+ if (closeOnAutoClose())
{
return null;
}
@@ -380,7 +406,7 @@ public class BasicMessageConsumer extends Closeable implements MessageConsumer
private boolean closeOnAutoClose() throws JMSException
{
- if(isAutoClose() && _closeWhenNoMessages && _synchronousQueue.isEmpty())
+ if (isAutoClose() && _closeWhenNoMessages && _synchronousQueue.isEmpty())
{
close(false);
return true;
@@ -393,13 +419,15 @@ public class BasicMessageConsumer extends Closeable implements MessageConsumer
public Message receiveNoWait() throws JMSException
{
- checkPreConditions();
+ _session.startDistpatcherIfNecessary();
+
+ checkPreConditions();
acquireReceiving();
try
{
- if(closeOnAutoClose())
+ if (closeOnAutoClose())
{
return null;
}
@@ -459,17 +487,16 @@ public class BasicMessageConsumer extends Closeable implements MessageConsumer
public void close(boolean sendClose) throws JMSException
{
- synchronized(_connection.getFailoverMutex())
+ synchronized (_connection.getFailoverMutex())
{
if (!_closed.getAndSet(true))
{
- if(sendClose)
+ if (sendClose)
{
- // AMQP version change: Hardwire the version to 0-9 (major=0, minor=9)
- // TODO: Connect this to the session version obtained from ProtocolInitiation for this session.
// Be aware of possible changes to parameter order as versions change.
final AMQMethodBody cancelBody = MessageCancelBody.createMethodBody(
- (byte)0, (byte)9, // AMQP version (major, minor)
+ _protocolHandler.getProtocolMajorVersion(), // AMQP major version
+ _protocolHandler.getProtocolMinorVersion(), // AMQP minor version
_consumerTag); // consumerTag
try
@@ -514,22 +541,50 @@ public class BasicMessageConsumer extends Closeable implements MessageConsumer
*/
void notifyMessage(UnprocessedMessage messageFrame, int channelId)
{
- if (_logger.isDebugEnabled())
+ final boolean debug = _logger.isDebugEnabled();
+
+ if (debug)
{
- _logger.debug("notifyMessage called with message number " + messageFrame.deliveryTag);
+ _logger.debug("notifyMessage called with message number " + messageFrame.getDeliveryTag());
}
try
{
- AbstractJMSMessage jmsMessage = _messageFactory.createMessage(messageFrame.deliveryTag,
+ AbstractJMSMessage jmsMessage = _messageFactory.createMessage(messageFrame.getDeliveryTag(),
false,
- messageFrame.contentHeader,
- messageFrame.contents);
+ messageFrame.getMessageHeaders(),
+ messageFrame.getContents());
- _logger.debug("Message is of type: " + jmsMessage.getClass().getName());
+ if (debug)
+ {
+ _logger.debug("Message is of type: " + jmsMessage.getClass().getName());
+ }
jmsMessage.setConsumer(this);
preDeliver(jmsMessage);
+ notifyMessage(jmsMessage, channelId);
+ }
+ catch (Exception e)
+ {
+ if (e instanceof InterruptedException)
+ {
+ _logger.info("SynchronousQueue.put interupted. Usually result of connection closing");
+ }
+ else
+ {
+ _logger.error("Caught exception (dump follows) - ignoring...", e);
+ }
+ }
+ }
+
+ /**
+ * @param jmsMessage this message has already been processed so can't redo preDeliver
+ * @param channelId
+ */
+ public void notifyMessage(AbstractJMSMessage jmsMessage, int channelId)
+ {
+ try
+ {
if (isMessageListenerSet())
{
//we do not need a lock around the test above, and the dispatch below as it is invalid
@@ -540,6 +595,7 @@ public class BasicMessageConsumer extends Closeable implements MessageConsumer
}
else
{
+ //This shouldn't be possible.
_synchronousQueue.put(jmsMessage);
}
}
@@ -547,11 +603,11 @@ public class BasicMessageConsumer extends Closeable implements MessageConsumer
{
if (e instanceof InterruptedException)
{
- _logger.info("SynchronousQueue.put interupted. Usually result of connection closing");
+ _logger.info("reNotification : SynchronousQueue.put interupted. Usually result of connection closing");
}
else
{
- _logger.error("Caught exception (dump follows) - ignoring...", e);
+ _logger.error("reNotification : Caught exception (dump follows) - ignoring...", e);
}
}
}
@@ -573,7 +629,7 @@ public class BasicMessageConsumer extends Closeable implements MessageConsumer
private void postDeliver(AbstractJMSMessage msg) throws JMSException, AMQException
{
- msg.setJMSDestination(_destination);
+ msg.setJMSDestination(_destination);
switch (_acknowledgeMode)
{
case Session.CLIENT_ACKNOWLEDGE:
@@ -636,6 +692,8 @@ public class BasicMessageConsumer extends Closeable implements MessageConsumer
{
_closed.set(true);
+ //QPID-293 can "request redelivery of this error through dispatcher"
+
// we have no way of propagating the exception to a message listener - a JMS limitation - so we
// deal with the case where we have a synchronous receive() waiting for a message to arrive
if (!isMessageListenerSet())
@@ -649,41 +707,45 @@ public class BasicMessageConsumer extends Closeable implements MessageConsumer
deregisterConsumer();
}
+
/**
* Perform cleanup to deregister this consumer. This occurs when closing the consumer in both the clean
* case and in the case of an error occurring.
*/
private void deregisterConsumer()
{
- _session.deregisterConsumer(this);
+ _session.deregisterConsumer(this);
}
- public String getConsumerTag()
+ public AMQShortString getConsumerTag()
{
return _consumerTag;
}
- public void setConsumerTag(String consumerTag)
+ public void setConsumerTag(AMQShortString consumerTag)
{
_consumerTag = consumerTag;
}
- public AMQSession getSession() {
- return _session;
- }
+ public AMQSession getSession()
+ {
+ return _session;
+ }
- private void checkPreConditions() throws JMSException{
+ private void checkPreConditions() throws JMSException
+ {
- this.checkNotClosed();
+ this.checkNotClosed();
- if(_session == null || _session.isClosed()){
- throw new javax.jms.IllegalStateException("Invalid Session");
- }
- }
+ if (_session == null || _session.isClosed())
+ {
+ throw new javax.jms.IllegalStateException("Invalid Session");
+ }
+ }
public void acknowledge() throws JMSException
{
- if(!isClosed())
+ if (!isClosed())
{
try
{
@@ -728,10 +790,10 @@ public class BasicMessageConsumer extends Closeable implements MessageConsumer
{
_closeWhenNoMessages = b;
- if(_closeWhenNoMessages
- && _synchronousQueue.isEmpty()
- && _receiving.get()
- && _messageListener != null)
+ if (_closeWhenNoMessages
+ && _synchronousQueue.isEmpty()
+ && _receiving.get()
+ && _messageListener != null)
{
_receivingThread.interrupt();
}
diff --git a/java/client/src/main/java/org/apache/qpid/client/BasicMessageProducer.java b/java/client/src/main/java/org/apache/qpid/client/BasicMessageProducer.java
index 39c4c28baf..7063ad62d1 100644
--- a/java/client/src/main/java/org/apache/qpid/client/BasicMessageProducer.java
+++ b/java/client/src/main/java/org/apache/qpid/client/BasicMessageProducer.java
@@ -26,6 +26,7 @@ import org.apache.qpid.AMQException;
import org.apache.qpid.client.message.AbstractJMSMessage;
import org.apache.qpid.client.message.JMSBytesMessage;
import org.apache.qpid.client.message.MessageHeaders;
+import org.apache.qpid.client.message.MessageConverter;
import org.apache.qpid.client.protocol.AMQProtocolHandler;
import org.apache.qpid.framing.*;
@@ -139,11 +140,10 @@ public class BasicMessageProducer extends Closeable implements org.apache.qpid.j
{
// Declare the exchange
// Note that the durable and internal arguments are ignored since passive is set to false
- // AMQP version change: Hardwire the version to 0-9 (major=0, minor=9)
- // TODO: Connect this to the session version obtained from ProtocolInitiation for this session.
// Be aware of possible changes to parameter order as versions change.
AMQMethodBody methodBody = ExchangeDeclareBody.createMethodBody(
- (byte)0, (byte)9, // AMQP version (major, minor)
+ _protocolHandler.getProtocolMajorVersion(), // AMQP major version
+ _protocolHandler.getProtocolMinorVersion(), // AMQP minor version
null, // arguments
false, // autoDelete
false, // durable
@@ -256,6 +256,19 @@ public class BasicMessageProducer extends Closeable implements org.apache.qpid.j
}
}
+ public void sendRef(Message message) throws JMSException
+ {
+ checkPreConditions();
+ checkInitialDestination();
+
+
+ synchronized (_connection.getFailoverMutex())
+ {
+ sendImpl(_destination, message, true, _deliveryMode, _messagePriority, _timeToLive,
+ _mandatory, _immediate);
+ }
+ }
+
public void send(Message message, int deliveryMode) throws JMSException
{
checkPreConditions();
@@ -373,112 +386,31 @@ public class BasicMessageProducer extends Closeable implements org.apache.qpid.j
if (message instanceof BytesMessage)
{
- BytesMessage bytesMessage = (BytesMessage) message;
- bytesMessage.reset();
-
- JMSBytesMessage nativeMsg = (JMSBytesMessage) _session.createBytesMessage();
-
-
- byte[] buf = new byte[1024];
-
- int len;
-
- while ((len = bytesMessage.readBytes(buf)) != -1)
- {
- nativeMsg.writeBytes(buf, 0, len);
- }
-
- newMessage = nativeMsg;
+ newMessage = new MessageConverter((BytesMessage)message).getConvertedMessage();
}
else if (message instanceof MapMessage)
{
- MapMessage origMessage = (MapMessage) message;
- MapMessage nativeMessage = _session.createMapMessage();
-
- Enumeration mapNames = origMessage.getMapNames();
- while (mapNames.hasMoreElements())
- {
- String name = (String) mapNames.nextElement();
- nativeMessage.setObject(name, origMessage.getObject(name));
- }
- newMessage = (AbstractJMSMessage) nativeMessage;
+ newMessage = new MessageConverter((MapMessage)message).getConvertedMessage();
}
else if (message instanceof ObjectMessage)
{
- ObjectMessage origMessage = (ObjectMessage) message;
- ObjectMessage nativeMessage = _session.createObjectMessage();
-
- nativeMessage.setObject(origMessage.getObject());
-
- newMessage = (AbstractJMSMessage) nativeMessage;
+ newMessage = new MessageConverter((ObjectMessage)message).getConvertedMessage();
}
else if (message instanceof TextMessage)
{
- TextMessage origMessage = (TextMessage) message;
- TextMessage nativeMessage = _session.createTextMessage();
-
- nativeMessage.setText(origMessage.getText());
-
- newMessage = (AbstractJMSMessage) nativeMessage;
+ newMessage = new MessageConverter((TextMessage)message).getConvertedMessage();
}
else if (message instanceof StreamMessage)
{
- StreamMessage origMessage = (StreamMessage) message;
- StreamMessage nativeMessage = _session.createStreamMessage();
-
-
- try
- {
- origMessage.reset();
- while (true)
- {
- nativeMessage.writeObject(origMessage.readObject());
- }
- }
- catch (MessageEOFException e)
- {
- ;//
- }
- newMessage = (AbstractJMSMessage) nativeMessage;
+ newMessage = new MessageConverter((StreamMessage)message).getConvertedMessage();
}
else
{
+ //TODO; Do we really want to create an empty message here ?
newMessage = (AbstractJMSMessage) _session.createMessage();
-
- }
-
- Enumeration propertyNames = message.getPropertyNames();
- while (propertyNames.hasMoreElements())
- {
- String propertyName = String.valueOf(propertyNames.nextElement());
- if (!propertyName.startsWith("JMSX_"))
- {
- Object value = message.getObjectProperty(propertyName);
- newMessage.setObjectProperty(propertyName, value);
- }
- }
-
- newMessage.setJMSDeliveryMode(message.getJMSDeliveryMode());
-
-
- int priority = message.getJMSPriority();
- if (priority < 0)
- {
- priority = 0;
- }
- else if (priority > 9)
- {
- priority = 9;
+ return new MessageConverter(newMessage).getConvertedMessage();
}
- newMessage.setJMSPriority(priority);
- if (message.getJMSReplyTo() != null)
- {
- newMessage.setJMSReplyTo(message.getJMSReplyTo());
- }
- newMessage.setJMSType(message.getJMSType());
-
-
if (newMessage != null)
{
return newMessage;
@@ -511,7 +443,13 @@ public class BasicMessageProducer extends Closeable implements org.apache.qpid.j
protected void sendImpl(AMQDestination destination, Message message, int deliveryMode, int priority,
long timeToLive, boolean mandatory, boolean immediate) throws JMSException
{
- sendImpl(destination, message, deliveryMode, priority, timeToLive, mandatory, immediate, _waitUntilSent);
+ sendImpl(destination, message, false, deliveryMode, priority, timeToLive, mandatory, immediate, _waitUntilSent);
+ }
+
+ protected void sendImpl(AMQDestination destination, Message message, boolean forceRef, int deliveryMode, int priority,
+ long timeToLive, boolean mandatory, boolean immediate) throws JMSException
+ {
+ sendImpl(destination, message, forceRef, deliveryMode, priority, timeToLive, mandatory, immediate, _waitUntilSent);
}
/**
@@ -530,11 +468,18 @@ public class BasicMessageProducer extends Closeable implements org.apache.qpid.j
long timeToLive, boolean mandatory, boolean immediate, boolean wait)
throws JMSException
{
+ sendImpl(destination, origMessage, false, deliveryMode, priority, timeToLive, mandatory, immediate, wait);
+ }
+
+ protected void sendImpl(AMQDestination destination, Message origMessage, boolean forceRef, int deliveryMode, int priority,
+ long timeToLive, boolean mandatory, boolean immediate, boolean wait)
+ throws JMSException
+ {
checkTemporaryDestination(destination);
origMessage.setJMSDestination(destination);
AbstractJMSMessage message = convertToNativeMessage(origMessage);
- message.getMessageHeaders().getJMSHeaders().setString(CustomJMXProperty.JMSX_QPID_JMSDESTINATIONURL.toString(), destination.toURL());
+ message.getMessageHeaders().getJMSHeaders().setString(CustomJMSXProperty.JMSZ_QPID_DESTTYPE.toString(), destination.toURL());
long currentTime = 0;
if (!_disableTimestamps)
@@ -564,7 +509,8 @@ public class BasicMessageProducer extends Closeable implements org.apache.qpid.j
int size = (payload != null) ? payload.limit() : 0;
final long framePayloadMax = _session.getAMQConnection().getMaximumFrameSize();
- if(_logger.isDebugEnabled()){
+ if(_logger.isDebugEnabled())
+ {
_logger.debug("framePayloadMax " + framePayloadMax);
_logger.debug("size " + size);
_logger.debug("payload capacity" + payload.capacity());
@@ -573,14 +519,17 @@ public class BasicMessageProducer extends Closeable implements org.apache.qpid.j
_logger.debug("payload position" + payload.position());
}
- if (size < framePayloadMax){
+ if (size < framePayloadMax && !forceRef)
+ {
// Inline message case
_logger.debug("Inline case, sending data inline with the transfer method");
Content data = new Content(Content.TypeEnum.INLINE_T, payload);
doMessageTransfer(messageHeaders,destination,data,message,deliveryMode,priority,timeToLive,mandatory,immediate);
- } else {
+ }
+ else
+ {
// Reference message case
// Sequence is as follows
// 1. Message.open
@@ -602,7 +551,8 @@ public class BasicMessageProducer extends Closeable implements org.apache.qpid.j
doMessageTransfer(messageHeaders,destination,data,message,deliveryMode,priority,timeToLive,mandatory,immediate);
//Message.Append
- for(Iterator it = content.iterator(); it.hasNext();){
+ for(Iterator it = content.iterator(); it.hasNext();)
+ {
doMessageAppend(referenceId,(byte[])it.next());
}
@@ -621,12 +571,16 @@ public class BasicMessageProducer extends Closeable implements org.apache.qpid.j
}
}
- private void doMessageTransfer(MessageHeaders messageHeaders,AMQDestination destination, Content content, AbstractJMSMessage message, int deliveryMode, int priority,
- long timeToLive, boolean mandatory, boolean immediate)throws JMSException{
+ private void doMessageTransfer(MessageHeaders messageHeaders, AMQDestination destination, Content content,
+ AbstractJMSMessage message, int deliveryMode, int priority,
+ long timeToLive, boolean mandatory, boolean immediate) throws JMSException
+ {
try
{
+ // Be aware of possible changes to parameter order as versions change.
AMQMethodBody methodBody = MessageTransferBody.createMethodBody(
- (byte)0, (byte)9, // AMQP version (major, minor)
+ _protocolHandler.getProtocolMajorVersion(), // AMQP major version
+ _protocolHandler.getProtocolMinorVersion(), // AMQP minor version
messageHeaders.getAppId(), // String appId
messageHeaders.getJMSHeaders(), // FieldTable applicationHeaders
content, // Content body
@@ -659,16 +613,56 @@ public class BasicMessageProducer extends Closeable implements org.apache.qpid.j
}
}
- private void doMessageOpen(String referenceId){
- AMQMethodBody methodBody = MessageOpenBody.createMethodBody((byte)0, (byte)9, referenceId.getBytes());
+ private void doMessageOpen(String referenceId) throws JMSException
+ {
+ try
+ {
+ // Be aware of possible changes to parameter order as versions change.
+ AMQMethodBody methodBody = MessageOpenBody.createMethodBody(
+ _protocolHandler.getProtocolMajorVersion(), // AMQP major version
+ _protocolHandler.getProtocolMinorVersion(), // AMQP minor version
+ referenceId.getBytes());
+ _protocolHandler.writeRequest(_channelId, methodBody);
+ }
+ catch (AMQException e)
+ {
+ throw new JMSException(e.toString());
+ }
}
- private void doMessageAppend(String referenceId,byte[] data){
- AMQMethodBody methodBody = MessageAppendBody.createMethodBody((byte)0, (byte)9, data, referenceId.getBytes());
+ private void doMessageAppend(String referenceId, byte[] data) throws JMSException
+ {
+ try
+ {
+ // Be aware of possible changes to parameter order as versions change.
+ AMQMethodBody methodBody = MessageAppendBody.createMethodBody(
+ _protocolHandler.getProtocolMajorVersion(), // AMQP major version
+ _protocolHandler.getProtocolMinorVersion(), // AMQP minor version
+ data,
+ referenceId.getBytes());
+ _protocolHandler.writeRequest(_channelId, methodBody);
+ }
+ catch (AMQException e)
+ {
+ throw new JMSException(e.toString());
+ }
}
- private void doMessageClose(String referenceId){
- AMQMethodBody methodBody = MessageCloseBody.createMethodBody((byte)0, (byte)9, referenceId.getBytes());
+ private void doMessageClose(String referenceId) throws JMSException
+ {
+ try
+ {
+ // Be aware of possible changes to parameter order as versions change.
+ AMQMethodBody methodBody = MessageCloseBody.createMethodBody(
+ _protocolHandler.getProtocolMajorVersion(), // AMQP major version
+ _protocolHandler.getProtocolMinorVersion(), // AMQP minor version
+ referenceId.getBytes());
+ _protocolHandler.writeRequest(_channelId, methodBody);
+ }
+ catch (AMQException e)
+ {
+ throw new JMSException(e.toString());
+ }
}
private String generateReferenceId(){
@@ -699,23 +693,28 @@ public class BasicMessageProducer extends Closeable implements org.apache.qpid.j
* maximum frame size.
*
* @param payload
+ * @param frames
+ * @param offset
+ * @param channelId
* @return the array of content bodies
*/
- private List createContent(ByteBuffer payload)
+ private List<byte[]> createContent(ByteBuffer payload)
{
int dataLength = payload.remaining();
final long framePayloadMax = _session.getAMQConnection().getMaximumFrameSize();
int lastFrame = (dataLength % framePayloadMax) > 0 ? 1 : 0;
int frameCount = (int) (dataLength / framePayloadMax) + lastFrame;
- List bodies = new LinkedList();
+ List<byte[]> bodies = new LinkedList<byte[]>();
long remaining = dataLength;
- for (int i = 0; i < frameCount + lastFrame; i++)
+ for (int i = 0; i < frameCount; i++)
{
payload.position((int) framePayloadMax * i);
int length = (remaining >= framePayloadMax) ? (int) framePayloadMax : (int) remaining;
payload.limit(payload.position() + length);
- bodies.add(payload.slice().array());
+ byte[] ba = new byte[length];
+ payload.slice().get(ba);
+ bodies.add(ba);
remaining -= length;
}
return bodies;
@@ -762,11 +761,8 @@ public class BasicMessageProducer extends Closeable implements org.apache.qpid.j
{
throw new InvalidDestinationException("Supplied Destination was invalid");
}
-
-
}
-
public AMQSession getSession()
{
return _session;
diff --git a/java/client/src/main/java/org/apache/qpid/client/CustomJMXProperty.java b/java/client/src/main/java/org/apache/qpid/client/CustomJMSXProperty.java
index 56cd4f3aa3..dc354a4b0d 100644
--- a/java/client/src/main/java/org/apache/qpid/client/CustomJMXProperty.java
+++ b/java/client/src/main/java/org/apache/qpid/client/CustomJMSXProperty.java
@@ -20,24 +20,39 @@
*/
package org.apache.qpid.client;
+import org.apache.qpid.framing.AMQShortString;
+
import java.util.*;
-public enum CustomJMXProperty
+public enum CustomJMSXProperty
{
- JMSX_QPID_JMSDESTINATIONURL,
+ JMSZ_QPID_DESTTYPE,
JMSXGroupID,
JMSXGroupSeq,
JMSXType;
+
+ private final AMQShortString _nameAsShortString;
+
+ CustomJMSXProperty()
+ {
+ _nameAsShortString = new AMQShortString(toString());
+ }
+
+ public AMQShortString getShortStringName()
+ {
+ return _nameAsShortString;
+ }
+
private static Enumeration _names;
public static synchronized Enumeration asEnumeration()
{
if(_names == null)
{
- CustomJMXProperty[] properties = values();
+ CustomJMSXProperty[] properties = values();
ArrayList<String> nameList = new ArrayList<String>(properties.length);
- for(CustomJMXProperty property : properties)
+ for(CustomJMSXProperty property : properties)
{
nameList.add(property.toString());
}
diff --git a/java/client/src/main/java/org/apache/qpid/client/DispatcherCallback.java b/java/client/src/main/java/org/apache/qpid/client/DispatcherCallback.java
new file mode 100644
index 0000000000..81a55006ed
--- /dev/null
+++ b/java/client/src/main/java/org/apache/qpid/client/DispatcherCallback.java
@@ -0,0 +1,36 @@
+/*
+ * 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.client;
+
+import java.util.Queue;
+
+public abstract class DispatcherCallback
+{
+ BasicMessageConsumer _consumer;
+
+ public DispatcherCallback(BasicMessageConsumer mc)
+ {
+ _consumer = mc;
+ }
+
+ abstract public void whilePaused(Queue<MessageConsumerPair> reprocessQueue);
+
+}
diff --git a/java/client/src/main/java/org/apache/qpid/client/MessageConsumerPair.java b/java/client/src/main/java/org/apache/qpid/client/MessageConsumerPair.java
new file mode 100644
index 0000000000..585d6db3fd
--- /dev/null
+++ b/java/client/src/main/java/org/apache/qpid/client/MessageConsumerPair.java
@@ -0,0 +1,43 @@
+/*
+ * 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.client;
+
+public class MessageConsumerPair
+{
+ BasicMessageConsumer _consumer;
+ Object _item;
+
+ public MessageConsumerPair(BasicMessageConsumer consumer, Object item)
+ {
+ _consumer = consumer;
+ _item = item;
+ }
+
+ public BasicMessageConsumer getConsumer()
+ {
+ return _consumer;
+ }
+
+ public Object getItem()
+ {
+ return _item;
+ }
+}
diff --git a/java/client/src/main/java/org/apache/qpid/client/QpidConnectionMetaData.java b/java/client/src/main/java/org/apache/qpid/client/QpidConnectionMetaData.java
index 9ee802ff10..7749bded2c 100644
--- a/java/client/src/main/java/org/apache/qpid/client/QpidConnectionMetaData.java
+++ b/java/client/src/main/java/org/apache/qpid/client/QpidConnectionMetaData.java
@@ -56,7 +56,7 @@ public class QpidConnectionMetaData implements ConnectionMetaData
public Enumeration getJMSXPropertyNames() throws JMSException
{
- return CustomJMXProperty.asEnumeration();
+ return CustomJMSXProperty.asEnumeration();
}
public int getProviderMajorVersion() throws JMSException
diff --git a/java/client/src/main/java/org/apache/qpid/client/failover/FailoverHandler.java b/java/client/src/main/java/org/apache/qpid/client/failover/FailoverHandler.java
index 50596d4bfc..7b789aa09d 100644
--- a/java/client/src/main/java/org/apache/qpid/client/failover/FailoverHandler.java
+++ b/java/client/src/main/java/org/apache/qpid/client/failover/FailoverHandler.java
@@ -82,8 +82,6 @@ public class FailoverHandler implements Runnable
// client code which runs in a separate thread.
synchronized (_amqProtocolHandler.getConnection().getFailoverMutex())
{
- _logger.info("Starting failover process");
-
// We switch in a new state manager temporarily so that the interaction to get to the "connection open"
// state works, without us having to terminate any existing "state waiters". We could theoretically
// have a state waiter waiting until the connection is closed for some reason. Or in future we may have
@@ -92,6 +90,8 @@ public class FailoverHandler implements Runnable
_amqProtocolHandler.setStateManager(new AMQStateManager(_amqProtocolHandler.getProtocolSession()));
if (!_amqProtocolHandler.getConnection().firePreFailover(_host != null))
{
+ _logger.info("Failover process veto-ed by client");
+
_amqProtocolHandler.setStateManager(existingStateManager);
if (_host != null)
{
@@ -105,6 +105,9 @@ public class FailoverHandler implements Runnable
_amqProtocolHandler.setFailoverLatch(null);
return;
}
+
+ _logger.info("Starting failover process");
+
boolean failoverSucceeded;
// when host is non null we have a specified failover host otherwise we all the client to cycle through
// all specified hosts
diff --git a/java/client/src/main/java/org/apache/qpid/client/failover/FailoverSupport.java b/java/client/src/main/java/org/apache/qpid/client/failover/FailoverSupport.java
index bb7397f194..2e08d303c8 100644
--- a/java/client/src/main/java/org/apache/qpid/client/failover/FailoverSupport.java
+++ b/java/client/src/main/java/org/apache/qpid/client/failover/FailoverSupport.java
@@ -56,7 +56,7 @@ public abstract class FailoverSupport
}
catch (FailoverException e)
{
- _log.info("Failover exception caught during operation");
+ _log.info("Failover exception caught during operation: " + e, e);
}
}
}
diff --git a/java/client/src/main/java/org/apache/qpid/client/handler/ChannelCloseMethodHandler.java b/java/client/src/main/java/org/apache/qpid/client/handler/ChannelCloseMethodHandler.java
index 0007ee8b5f..3ae13f949c 100644
--- a/java/client/src/main/java/org/apache/qpid/client/handler/ChannelCloseMethodHandler.java
+++ b/java/client/src/main/java/org/apache/qpid/client/handler/ChannelCloseMethodHandler.java
@@ -20,7 +20,6 @@
*/
package org.apache.qpid.client.handler;
-import org.apache.log4j.Logger;
import org.apache.qpid.AMQChannelClosedException;
import org.apache.qpid.AMQException;
import org.apache.qpid.AMQInvalidSelectorException;
@@ -29,13 +28,15 @@ import org.apache.qpid.client.AMQNoRouteException;
import org.apache.qpid.client.protocol.AMQProtocolSession;
import org.apache.qpid.client.state.AMQStateManager;
import org.apache.qpid.client.state.StateAwareMethodListener;
-import org.apache.qpid.framing.AMQFrame;
import org.apache.qpid.framing.AMQMethodBody;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.framing.ChannelCloseBody;
import org.apache.qpid.framing.ChannelCloseOkBody;
import org.apache.qpid.protocol.AMQConstant;
import org.apache.qpid.protocol.AMQMethodEvent;
+import org.apache.log4j.Logger;
+
public class ChannelCloseMethodHandler implements StateAwareMethodListener
{
private static final Logger _logger = Logger.getLogger(ChannelCloseMethodHandler.class);
@@ -46,24 +47,27 @@ public class ChannelCloseMethodHandler implements StateAwareMethodListener
{
return _handler;
}
+
+ private ChannelCloseMethodHandler() {}
public void methodReceived(AMQStateManager stateManager, AMQProtocolSession protocolSession, AMQMethodEvent evt) throws AMQException
{
_logger.debug("ChannelClose method received");
- ChannelCloseBody method = (ChannelCloseBody) evt.getMethod();
+ final ChannelCloseBody method = (ChannelCloseBody) evt.getMethod();
int errorCode = method.replyCode;
- String reason = method.replyText;
+ String reason = method.replyText.asString();
if (_logger.isDebugEnabled())
{
_logger.debug("Channel close reply code: " + errorCode + ", reason: " + reason);
}
- // AMQP version change: Hardwire the version to 0-9 (major=0, minor=9)
- // TODO: Connect this to the session version obtained from ProtocolInitiation for this session.
// Be aware of possible changes to parameter order as versions change.
- AMQMethodBody methodBody = ChannelCloseOkBody.createMethodBody((byte)0, (byte)9);
+ AMQMethodBody methodBody = ChannelCloseOkBody.createMethodBody(
+ protocolSession.getProtocolMajorVersion(), // AMQP major version
+ protocolSession.getProtocolMinorVersion()); // AMQP minor version
protocolSession.writeResponse(evt.getChannelId(), evt.getRequestId(), methodBody);
+
if (errorCode != AMQConstant.REPLY_SUCCESS.getCode())
{
_logger.error("Channel close received with errorCode " + errorCode + ", and reason " + reason);
@@ -79,13 +83,12 @@ public class ChannelCloseMethodHandler implements StateAwareMethodListener
{
_logger.info("Broker responded with Invalid Selector.");
- throw new AMQInvalidSelectorException(reason);
+ throw new AMQInvalidSelectorException(String.valueOf(reason));
}
else
{
throw new AMQChannelClosedException(errorCode, "Error: " + reason);
}
-
}
protocolSession.channelClosed(evt.getChannelId(), errorCode, reason);
}
diff --git a/java/client/src/main/java/org/apache/qpid/client/handler/ChannelCloseOkMethodHandler.java b/java/client/src/main/java/org/apache/qpid/client/handler/ChannelCloseOkMethodHandler.java
index a99c963eb4..4aef4bc1b6 100644
--- a/java/client/src/main/java/org/apache/qpid/client/handler/ChannelCloseOkMethodHandler.java
+++ b/java/client/src/main/java/org/apache/qpid/client/handler/ChannelCloseOkMethodHandler.java
@@ -21,10 +21,11 @@
package org.apache.qpid.client.handler;
import org.apache.qpid.AMQException;
-import org.apache.qpid.protocol.AMQMethodEvent;
import org.apache.qpid.client.protocol.AMQProtocolSession;
import org.apache.qpid.client.state.AMQStateManager;
import org.apache.qpid.client.state.StateAwareMethodListener;
+import org.apache.qpid.protocol.AMQMethodEvent;
+
import org.apache.log4j.Logger;
public class ChannelCloseOkMethodHandler implements StateAwareMethodListener
@@ -37,6 +38,8 @@ public class ChannelCloseOkMethodHandler implements StateAwareMethodListener
{
return _instance;
}
+
+ private ChannelCloseOkMethodHandler() {}
public void methodReceived(AMQStateManager stateManager, AMQProtocolSession protocolSession, AMQMethodEvent evt) throws AMQException
{
diff --git a/java/client/src/main/java/org/apache/qpid/client/handler/ChannelFlowOkMethodHandler.java b/java/client/src/main/java/org/apache/qpid/client/handler/ChannelFlowOkMethodHandler.java
index 7a13972d8f..e21ab5cba1 100644
--- a/java/client/src/main/java/org/apache/qpid/client/handler/ChannelFlowOkMethodHandler.java
+++ b/java/client/src/main/java/org/apache/qpid/client/handler/ChannelFlowOkMethodHandler.java
@@ -20,31 +20,31 @@
*/
package org.apache.qpid.client.handler;
-import org.apache.log4j.Logger;
import org.apache.qpid.AMQException;
-import org.apache.qpid.protocol.AMQMethodEvent;
import org.apache.qpid.client.protocol.AMQProtocolSession;
import org.apache.qpid.client.state.AMQStateManager;
import org.apache.qpid.client.state.StateAwareMethodListener;
import org.apache.qpid.framing.ChannelFlowOkBody;
+import org.apache.qpid.protocol.AMQMethodEvent;
+
+import org.apache.log4j.Logger;
public class ChannelFlowOkMethodHandler implements StateAwareMethodListener
{
- private static final Logger _logger = Logger.getLogger(ChannelFlowOkMethodHandler.class);
- private static final ChannelFlowOkMethodHandler _instance = new ChannelFlowOkMethodHandler();
+ private static final Logger _logger = Logger.getLogger(ChannelFlowOkMethodHandler.class);
+
+ private static final ChannelFlowOkMethodHandler _instance = new ChannelFlowOkMethodHandler();
- public static ChannelFlowOkMethodHandler getInstance()
- {
- return _instance;
- }
+ public static ChannelFlowOkMethodHandler getInstance()
+ {
+ return _instance;
+ }
- private ChannelFlowOkMethodHandler()
- {
- }
+ private ChannelFlowOkMethodHandler() {}
- public void methodReceived(AMQStateManager stateManager, AMQProtocolSession protocolSession, AMQMethodEvent evt) throws AMQException
- {
- ChannelFlowOkBody method = (ChannelFlowOkBody) evt.getMethod();
- _logger.debug("Received Channel.Flow-Ok message, active = " + method.active);
- }
+ public void methodReceived(AMQStateManager stateManager, AMQProtocolSession protocolSession, AMQMethodEvent evt) throws AMQException
+ {
+ ChannelFlowOkBody method = (ChannelFlowOkBody) evt.getMethod();
+ _logger.debug("Received Channel.Flow-Ok message, active = " + method.active);
+ }
}
diff --git a/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionCloseMethodHandler.java b/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionCloseMethodHandler.java
index 25acd2cb6b..a5fdd4779a 100644
--- a/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionCloseMethodHandler.java
+++ b/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionCloseMethodHandler.java
@@ -20,18 +20,20 @@
*/
package org.apache.qpid.client.handler;
-import org.apache.log4j.Logger;
import org.apache.qpid.AMQException;
import org.apache.qpid.AMQConnectionClosedException;
-import org.apache.qpid.protocol.AMQConstant;
-import org.apache.qpid.protocol.AMQMethodEvent;
import org.apache.qpid.client.protocol.AMQProtocolSession;
import org.apache.qpid.client.state.AMQState;
import org.apache.qpid.client.state.AMQStateManager;
import org.apache.qpid.client.state.StateAwareMethodListener;
import org.apache.qpid.client.AMQAuthenticationException;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.framing.ConnectionCloseBody;
import org.apache.qpid.framing.ConnectionCloseOkBody;
+import org.apache.qpid.protocol.AMQConstant;
+import org.apache.qpid.protocol.AMQMethodEvent;
+
+import org.apache.log4j.Logger;
public class ConnectionCloseMethodHandler implements StateAwareMethodListener
{
@@ -44,9 +46,7 @@ public class ConnectionCloseMethodHandler implements StateAwareMethodListener
return _handler;
}
- private ConnectionCloseMethodHandler()
- {
- }
+ private ConnectionCloseMethodHandler() {}
public void methodReceived(AMQStateManager stateManager, AMQProtocolSession protocolSession, AMQMethodEvent evt) throws AMQException
{
@@ -57,13 +57,13 @@ public class ConnectionCloseMethodHandler implements StateAwareMethodListener
//stateManager.changeState(AMQState.CONNECTION_CLOSING);
int errorCode = method.replyCode;
- String reason = method.replyText;
+ AMQShortString reason = method.replyText;
// TODO: check whether channel id of zero is appropriate
- // AMQP version change: Hardwire the version to 0-9 (major=0, minor=9)
- // TODO: Connect this to the session version obtained from ProtocolInitiation for this session.
// Be aware of possible changes to parameter order as versions change.
- protocolSession.writeResponse(0, evt.getRequestId(), ConnectionCloseOkBody.createMethodBody((byte)0, (byte)9));
+ protocolSession.writeResponse(0, evt.getRequestId(), ConnectionCloseOkBody.createMethodBody(
+ protocolSession.getProtocolMajorVersion(), // AMQP major version
+ protocolSession.getProtocolMinorVersion())); // AMQP minor version
if (errorCode != 200)
{
@@ -76,7 +76,7 @@ public class ConnectionCloseMethodHandler implements StateAwareMethodListener
//todo this is a bit of a fudge (could be conssidered such as each new connection needs a new state manager or at least a fresh state.
stateManager.changeState(AMQState.CONNECTION_NOT_STARTED);
- throw new AMQAuthenticationException(errorCode, reason);
+ throw new AMQAuthenticationException(errorCode, reason == null ? null : reason.toString());
}
else
{
diff --git a/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionOpenOkMethodHandler.java b/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionOpenOkMethodHandler.java
index da903e7c1d..877d91e676 100644
--- a/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionOpenOkMethodHandler.java
+++ b/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionOpenOkMethodHandler.java
@@ -21,14 +21,19 @@
package org.apache.qpid.client.handler;
import org.apache.qpid.AMQException;
-import org.apache.qpid.protocol.AMQMethodEvent;
import org.apache.qpid.client.protocol.AMQProtocolSession;
import org.apache.qpid.client.state.AMQState;
import org.apache.qpid.client.state.AMQStateManager;
import org.apache.qpid.client.state.StateAwareMethodListener;
+import org.apache.qpid.framing.ConnectionOpenOkBody;
+import org.apache.qpid.protocol.AMQMethodEvent;
+
+//import org.apache.log4j.Logger;
public class ConnectionOpenOkMethodHandler implements StateAwareMethodListener
{
+ //private static final Logger _logger = Logger.getLogger(ConnectionOpenOkMethodHandler.class);
+
private static final ConnectionOpenOkMethodHandler _instance = new ConnectionOpenOkMethodHandler();
public static ConnectionOpenOkMethodHandler getInstance()
@@ -36,13 +41,10 @@ public class ConnectionOpenOkMethodHandler implements StateAwareMethodListener
return _instance;
}
- private ConnectionOpenOkMethodHandler()
- {
- }
+ private ConnectionOpenOkMethodHandler() {}
public void methodReceived(AMQStateManager stateManager, AMQProtocolSession protocolSession, AMQMethodEvent evt) throws AMQException
{
stateManager.changeState(AMQState.CONNECTION_OPEN);
}
-
}
diff --git a/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionRedirectMethodHandler.java b/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionRedirectMethodHandler.java
index 699c8955bc..641a58f69b 100644
--- a/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionRedirectMethodHandler.java
+++ b/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionRedirectMethodHandler.java
@@ -20,13 +20,14 @@
*/
package org.apache.qpid.client.handler;
-import org.apache.log4j.Logger;
import org.apache.qpid.AMQException;
-import org.apache.qpid.protocol.AMQMethodEvent;
import org.apache.qpid.client.protocol.AMQProtocolSession;
import org.apache.qpid.client.state.AMQStateManager;
import org.apache.qpid.client.state.StateAwareMethodListener;
import org.apache.qpid.framing.ConnectionRedirectBody;
+import org.apache.qpid.protocol.AMQMethodEvent;
+
+import org.apache.log4j.Logger;
public class ConnectionRedirectMethodHandler implements StateAwareMethodListener
{
@@ -41,28 +42,27 @@ public class ConnectionRedirectMethodHandler implements StateAwareMethodListener
return _handler;
}
- private ConnectionRedirectMethodHandler()
- {
- }
+ private ConnectionRedirectMethodHandler() {}
public void methodReceived(AMQStateManager stateManager, AMQProtocolSession protocolSession, AMQMethodEvent evt) throws AMQException
{
_logger.info("ConnectionRedirect frame received");
ConnectionRedirectBody method = (ConnectionRedirectBody) evt.getMethod();
+ String host = method.host.toString();
// the host is in the form hostname:port with the port being optional
- int portIndex = method.host.indexOf(':');
- String host;
+ int portIndex = host.indexOf(':');
+
int port;
if (portIndex == -1)
{
- host = method.host;
port = DEFAULT_REDIRECT_PORT;
}
else
{
- host = method.host.substring(0, portIndex);
- port = Integer.parseInt(method.host.substring(portIndex + 1));
+ port = Integer.parseInt(host.substring(portIndex + 1));
+ host = host.substring(0, portIndex);
+
}
protocolSession.failover(host, port);
}
diff --git a/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionSecureMethodHandler.java b/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionSecureMethodHandler.java
index 94cf8b16c6..4b6963d2cf 100644
--- a/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionSecureMethodHandler.java
+++ b/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionSecureMethodHandler.java
@@ -21,26 +21,32 @@
package org.apache.qpid.client.handler;
import org.apache.qpid.AMQException;
+import org.apache.qpid.client.protocol.AMQProtocolSession;
+import org.apache.qpid.client.state.AMQStateManager;
+import org.apache.qpid.client.state.StateAwareMethodListener;
import org.apache.qpid.framing.AMQFrame;
import org.apache.qpid.framing.AMQMethodBody;
-import org.apache.qpid.framing.ConnectionSecureOkBody;
import org.apache.qpid.framing.ConnectionSecureBody;
+import org.apache.qpid.framing.ConnectionSecureOkBody;
import org.apache.qpid.protocol.AMQMethodEvent;
-import org.apache.qpid.client.protocol.AMQProtocolSession;
-import org.apache.qpid.client.state.AMQStateManager;
-import org.apache.qpid.client.state.StateAwareMethodListener;
+
+//import org.apache.log4j.Logger;
import javax.security.sasl.SaslClient;
import javax.security.sasl.SaslException;
public class ConnectionSecureMethodHandler implements StateAwareMethodListener
{
+ //private static final Logger _logger = Logger.getLogger(ConnectionSecureMethodHandler.class);
+
private static final ConnectionSecureMethodHandler _instance = new ConnectionSecureMethodHandler();
public static ConnectionSecureMethodHandler getInstance()
{
return _instance;
}
+
+ private ConnectionSecureMethodHandler() {}
public void methodReceived(AMQStateManager stateManager, AMQProtocolSession protocolSession, AMQMethodEvent evt) throws AMQException
{
@@ -56,10 +62,11 @@ public class ConnectionSecureMethodHandler implements StateAwareMethodListener
{
// Evaluate server challenge
byte[] response = client.evaluateChallenge(body.challenge);
- // AMQP version change: Hardwire the version to 0-9 (major=0, minor=9)
- // TODO: Connect this to the session version obtained from ProtocolInitiation for this session.
+
// Be aware of possible changes to parameter order as versions change.
- AMQMethodBody methodBody = ConnectionSecureOkBody.createMethodBody((byte)0, (byte)9, // AMQP version (major, minor)
+ AMQMethodBody methodBody = ConnectionSecureOkBody.createMethodBody(
+ protocolSession.getProtocolMajorVersion(), // AMQP major version
+ protocolSession.getProtocolMinorVersion(), // AMQP minor version
response); // response
protocolSession.writeResponse(evt.getChannelId(), evt.getRequestId(), methodBody);
}
@@ -67,7 +74,5 @@ public class ConnectionSecureMethodHandler implements StateAwareMethodListener
{
throw new AMQException("Error processing SASL challenge: " + e, e);
}
-
-
}
}
diff --git a/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionStartMethodHandler.java b/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionStartMethodHandler.java
index e58499f116..3e6bbcc3a5 100644
--- a/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionStartMethodHandler.java
+++ b/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionStartMethodHandler.java
@@ -20,22 +20,26 @@
*/
package org.apache.qpid.client.handler;
-import org.apache.log4j.Logger;
import org.apache.qpid.AMQException;
import org.apache.qpid.common.ClientProperties;
import org.apache.qpid.common.QpidProperties;
+import org.apache.qpid.protocol.AMQMethodEvent;
import org.apache.qpid.client.protocol.AMQProtocolSession;
import org.apache.qpid.client.security.AMQCallbackHandler;
import org.apache.qpid.client.security.CallbackHandlerRegistry;
import org.apache.qpid.client.state.AMQState;
import org.apache.qpid.client.state.AMQStateManager;
import org.apache.qpid.client.state.StateAwareMethodListener;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.framing.ConnectionStartBody;
import org.apache.qpid.framing.ConnectionStartOkBody;
import org.apache.qpid.framing.FieldTable;
import org.apache.qpid.framing.FieldTableFactory;
+import org.apache.qpid.framing.ProtocolVersionList;
import org.apache.qpid.protocol.AMQMethodEvent;
+import org.apache.log4j.Logger;
+
import javax.security.sasl.Sasl;
import javax.security.sasl.SaslClient;
import javax.security.sasl.SaslException;
@@ -45,7 +49,6 @@ import java.util.StringTokenizer;
public class ConnectionStartMethodHandler implements StateAwareMethodListener
{
-
private static final Logger _log = Logger.getLogger(ConnectionStartMethodHandler.class);
private static final ConnectionStartMethodHandler _instance = new ConnectionStartMethodHandler();
@@ -55,90 +58,110 @@ public class ConnectionStartMethodHandler implements StateAwareMethodListener
return _instance;
}
- private ConnectionStartMethodHandler()
- {
- }
+ private ConnectionStartMethodHandler() {}
public void methodReceived(AMQStateManager stateManager, AMQProtocolSession protocolSession, AMQMethodEvent evt) throws AMQException
{
ConnectionStartBody body = (ConnectionStartBody) evt.getMethod();
- try
- {
- // the mechanism we are going to use
- String mechanism;
- if (body.mechanisms == null)
- {
- throw new AMQException("mechanism not specified in ConnectionStart method frame");
- }
- else
- {
- mechanism = chooseMechanism(body.mechanisms);
- }
+ byte major = (byte) body.versionMajor;
+ byte minor = (byte) body.versionMinor;
- if (mechanism == null)
- {
- throw new AMQException("No supported security mechanism found, passed: " + new String(body.mechanisms));
- }
+ if(checkVersionOK(major, minor))
+ {
+ protocolSession.setProtocolVersion(major, minor);
- byte[] saslResponse;
try
{
- SaslClient sc = Sasl.createSaslClient(new String[]{mechanism},
+ // the mechanism we are going to use
+ String mechanism;
+ if (body.mechanisms == null)
+ {
+ throw new AMQException("mechanism not specified in ConnectionStart method frame");
+ }
+ else
+ {
+ mechanism = chooseMechanism(body.mechanisms);
+ }
+
+ if (mechanism == null)
+ {
+ throw new AMQException("No supported security mechanism found, passed: " + new String(body.mechanisms));
+ }
+
+ byte[] saslResponse;
+ try
+ {
+ SaslClient sc = Sasl.createSaslClient(new String[]{mechanism},
null, "AMQP", "localhost",
null, createCallbackHandler(mechanism, protocolSession));
- if (sc == null)
+ if (sc == null)
+ protocolSession.setSaslClient(sc);
+ saslResponse = (sc.hasInitialResponse() ? sc.evaluateChallenge(new byte[0]) : null);
+ }
+ catch (SaslException e)
{
- throw new AMQException("Client SASL configuration error: no SaslClient could be created for mechanism " +
- mechanism + ". Please ensure all factories are registered. See DynamicSaslRegistrar for " +
- " details of how to register non-standard SASL client providers.");
+ protocolSession.setSaslClient(null);
+ throw new AMQException("Unable to create SASL client: " + e, e);
}
- protocolSession.setSaslClient(sc);
- saslResponse = (sc.hasInitialResponse() ? sc.evaluateChallenge(new byte[0]) : null);
- }
- catch (SaslException e)
- {
- protocolSession.setSaslClient(null);
- throw new AMQException("Unable to create SASL client: " + e, e);
- }
- if (body.locales == null)
- {
- throw new AMQException("Locales is not defined in Connection Start method");
- }
- final String locales = new String(body.locales, "utf8");
- final StringTokenizer tokenizer = new StringTokenizer(locales, " ");
- String selectedLocale = null;
- if (tokenizer.hasMoreTokens())
- {
- selectedLocale = tokenizer.nextToken();
+ final String locales = new String(body.locales, "utf8");
+ final StringTokenizer tokenizer = new StringTokenizer(locales, " ");
+ String selectedLocale = null;
+ if (tokenizer.hasMoreTokens())
+ {
+ selectedLocale = tokenizer.nextToken();
+ }
+ else
+ {
+ throw new AMQException("No locales sent from server, passed: " + locales);
+ }
+
+ stateManager.changeState(AMQState.CONNECTION_NOT_TUNED);
+ FieldTable clientProperties = FieldTableFactory.newFieldTable();
+
+ clientProperties.put(new AMQShortString(ClientProperties.instance.toString()), protocolSession.getClientID());
+ clientProperties.put(new AMQShortString(ClientProperties.product.toString()), QpidProperties.getProductName());
+ clientProperties.put(new AMQShortString(ClientProperties.version.toString()), QpidProperties.getReleaseVersion());
+ clientProperties.put(new AMQShortString(ClientProperties.platform.toString()), getFullSystemInfo());
+
+ // Be aware of possible changes to parameter order as versions change.
+ protocolSession.writeResponse(evt.getChannelId(), evt.getRequestId(),
+ ConnectionStartOkBody.createMethodBody(major, minor, // AMQP version (major, minor)
+ clientProperties, // clientProperties
+ new AMQShortString(selectedLocale), // locale
+ new AMQShortString(mechanism), // mechanism
+ saslResponse)); // response
}
- else
+ catch (UnsupportedEncodingException e)
{
- throw new AMQException("No locales sent from server, passed: " + locales);
+ throw new AMQException(_log, "Unable to decode data: " + e, e);
}
+ }
+ else
+ {
+ _log.error("Broker requested Protocol ["
+ + body.versionMajor
+ + "-"
+ + body.versionMinor
+ + "] which is not supported by this version of the client library");
- stateManager.changeState(AMQState.CONNECTION_NOT_TUNED);
- FieldTable clientProperties = FieldTableFactory.newFieldTable();
-
- clientProperties.put(ClientProperties.instance.toString(), protocolSession.getClientID());
- clientProperties.put(ClientProperties.product.toString(), QpidProperties.getProductName());
- clientProperties.put(ClientProperties.version.toString(), QpidProperties.getReleaseVersion());
- clientProperties.put(ClientProperties.platform.toString(), getFullSystemInfo());
- // AMQP version change: Hardwire the version to 0-9 (major=0, minor=9)
- // TODO: Connect this to the session version obtained from ProtocolInitiation for this session.
- // Be aware of possible changes to parameter order as versions change.
- protocolSession.writeResponse(evt.getChannelId(), evt.getRequestId(),
- ConnectionStartOkBody.createMethodBody((byte)0, (byte)9, // AMQP version (major, minor)
- clientProperties, // clientProperties
- selectedLocale, // locale
- mechanism, // mechanism
- saslResponse)); // response
+ protocolSession.closeProtocolSession();
}
- catch (UnsupportedEncodingException e)
+ }
+
+ private boolean checkVersionOK(byte versionMajor, byte versionMinor)
+ {
+ byte[][] supportedVersions = ProtocolVersionList.pv;
+ boolean supported = false;
+ int i = supportedVersions.length;
+ while(i-- != 0 && !supported)
{
- throw new AMQException(_log, "Unable to decode data: " + e, e);
+ supported = (supportedVersions[i][ProtocolVersionList.PROTOCOL_MAJOR] == versionMajor)
+ && (supportedVersions[i][ProtocolVersionList.PROTOCOL_MINOR] == versionMinor);
}
+
+ return supported;
}
private String getFullSystemInfo()
diff --git a/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionTuneMethodHandler.java b/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionTuneMethodHandler.java
index f2524cfbc9..fd7c48b89f 100644
--- a/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionTuneMethodHandler.java
+++ b/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionTuneMethodHandler.java
@@ -20,20 +20,21 @@
*/
package org.apache.qpid.client.handler;
-import org.apache.log4j.Logger;
import org.apache.qpid.AMQException;
import org.apache.qpid.client.ConnectionTuneParameters;
import org.apache.qpid.client.protocol.AMQProtocolSession;
import org.apache.qpid.client.state.AMQState;
import org.apache.qpid.client.state.AMQStateManager;
import org.apache.qpid.client.state.StateAwareMethodListener;
+import org.apache.qpid.framing.AMQMethodBody;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.framing.ConnectionOpenBody;
import org.apache.qpid.framing.ConnectionTuneBody;
import org.apache.qpid.framing.ConnectionTuneOkBody;
-import org.apache.qpid.framing.AMQFrame;
-import org.apache.qpid.framing.AMQMethodBody;
import org.apache.qpid.protocol.AMQMethodEvent;
+import org.apache.log4j.Logger;
+
public class ConnectionTuneMethodHandler implements StateAwareMethodListener
{
private static final Logger _logger = Logger.getLogger(ConnectionTuneMethodHandler.class);
@@ -45,9 +46,7 @@ public class ConnectionTuneMethodHandler implements StateAwareMethodListener
return _instance;
}
- protected ConnectionTuneMethodHandler()
- {
- }
+ protected ConnectionTuneMethodHandler() {}
public void methodReceived(AMQStateManager stateManager, AMQProtocolSession protocolSession, AMQMethodEvent evt) throws AMQException
{
@@ -66,29 +65,31 @@ public class ConnectionTuneMethodHandler implements StateAwareMethodListener
protocolSession.setConnectionTuneParameters(params);
stateManager.changeState(AMQState.CONNECTION_NOT_OPENED);
- protocolSession.writeResponse(evt.getChannelId(), evt.getRequestId(), createTuneOkMethodBody(params));
+ protocolSession.writeResponse(evt.getChannelId(), evt.getRequestId(), createTuneOkMethodBody(protocolSession, params));
+ String host = protocolSession.getAMQConnection().getVirtualHost();
+ AMQShortString virtualHost = new AMQShortString("/" + host);
protocolSession.writeRequest(evt.getChannelId(),
- createConnectionOpenMethodBody(protocolSession.getAMQConnection().getVirtualHost(), null, true),
+ createConnectionOpenMethodBody(protocolSession, virtualHost, null, true),
protocolSession.getStateManager());
}
- protected AMQMethodBody createConnectionOpenMethodBody(String path, String capabilities, boolean insist)
+ protected AMQMethodBody createConnectionOpenMethodBody(AMQProtocolSession protocolSession, AMQShortString path, AMQShortString capabilities, boolean insist)
{
- // AMQP version change: Hardwire the version to 0-9 (major=0, minor=9)
- // TODO: Connect this to the session version obtained from ProtocolInitiation for this session.
// Be aware of possible changes to parameter order as versions change.
- return ConnectionOpenBody.createMethodBody((byte)0, (byte)9, // AMQP version (major, minor)
+ return ConnectionOpenBody.createMethodBody(
+ protocolSession.getProtocolMajorVersion(), // AMQP major version
+ protocolSession.getProtocolMinorVersion(), // AMQP minor version
capabilities, // capabilities
insist, // insist
path); // virtualHost
}
- protected AMQMethodBody createTuneOkMethodBody(ConnectionTuneParameters params)
+ protected AMQMethodBody createTuneOkMethodBody(AMQProtocolSession protocolSession, ConnectionTuneParameters params)
{
- // AMQP version change: Hardwire the version to 0-9 (major=0, minor=9)
- // TODO: Connect this to the session version obtained from ProtocolInitiation for this session.
// Be aware of possible changes to parameter order as versions change.
- return ConnectionTuneOkBody.createMethodBody((byte)0, (byte)9, // AMQP version (major, minor)
+ return ConnectionTuneOkBody.createMethodBody(
+ protocolSession.getProtocolMajorVersion(), // AMQP major version
+ protocolSession.getProtocolMinorVersion(), // AMQP minor version
params.getChannelMax(), // channelMax
params.getFrameMax(), // frameMax
params.getHeartbeat()); // heartbeat
diff --git a/java/client/src/main/java/org/apache/qpid/client/handler/ExchangeBoundOkMethodHandler.java b/java/client/src/main/java/org/apache/qpid/client/handler/ExchangeBoundOkMethodHandler.java
index 41e57113b0..8a35a3d77a 100644
--- a/java/client/src/main/java/org/apache/qpid/client/handler/ExchangeBoundOkMethodHandler.java
+++ b/java/client/src/main/java/org/apache/qpid/client/handler/ExchangeBoundOkMethodHandler.java
@@ -17,7 +17,6 @@
*/
package org.apache.qpid.client.handler;
-import org.apache.log4j.Logger;
import org.apache.qpid.AMQException;
import org.apache.qpid.client.protocol.AMQProtocolSession;
import org.apache.qpid.client.state.AMQStateManager;
@@ -25,31 +24,29 @@ import org.apache.qpid.client.state.StateAwareMethodListener;
import org.apache.qpid.framing.ExchangeBoundOkBody;
import org.apache.qpid.protocol.AMQMethodEvent;
-/**
- * @author Apache Software Foundation
- */
+import org.apache.log4j.Logger;
+
public class ExchangeBoundOkMethodHandler implements StateAwareMethodListener
{
- private static final Logger _logger = Logger.getLogger(ExchangeBoundOkMethodHandler.class);
- private static final ExchangeBoundOkMethodHandler _instance = new ExchangeBoundOkMethodHandler();
-
- public static ExchangeBoundOkMethodHandler getInstance()
- {
- return _instance;
- }
-
- private ExchangeBoundOkMethodHandler()
- {
- }
-
- public void methodReceived(AMQStateManager stateManager, AMQProtocolSession protocolSession, AMQMethodEvent evt) throws AMQException
- {
- if (_logger.isDebugEnabled())
- {
+ private static final Logger _logger = Logger.getLogger(ExchangeBoundOkMethodHandler.class);
+
+ private static final ExchangeBoundOkMethodHandler _instance = new ExchangeBoundOkMethodHandler();
+
+ public static ExchangeBoundOkMethodHandler getInstance()
+ {
+ return _instance;
+ }
+
+ private ExchangeBoundOkMethodHandler() {}
+
+ public void methodReceived(AMQStateManager stateManager, AMQProtocolSession protocolSession, AMQMethodEvent evt) throws AMQException
+ {
+ if (_logger.isDebugEnabled())
+ {
ExchangeBoundOkBody body = (ExchangeBoundOkBody) evt.getMethod();
_logger.debug("Received Exchange.Bound-Ok message, response code: " + body.replyCode + " text: " +
body.replyText);
- }
- }
+ }
+ }
}
diff --git a/java/client/src/main/java/org/apache/qpid/client/handler/MessageAppendMethodHandler.java b/java/client/src/main/java/org/apache/qpid/client/handler/MessageAppendMethodHandler.java
index 152a86ed63..361b63230f 100644
--- a/java/client/src/main/java/org/apache/qpid/client/handler/MessageAppendMethodHandler.java
+++ b/java/client/src/main/java/org/apache/qpid/client/handler/MessageAppendMethodHandler.java
@@ -20,35 +20,36 @@
*/
package org.apache.qpid.client.handler;
-import org.apache.log4j.Logger;
import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.MessageAppendBody;
-import org.apache.qpid.protocol.AMQMethodEvent;
import org.apache.qpid.client.protocol.AMQProtocolSession;
import org.apache.qpid.client.state.AMQStateManager;
import org.apache.qpid.client.state.StateAwareMethodListener;
+import org.apache.qpid.framing.MessageAppendBody;
+import org.apache.qpid.protocol.AMQMethodEvent;
+
+import org.apache.log4j.Logger;
public class MessageAppendMethodHandler implements StateAwareMethodListener
{
- private static MessageAppendMethodHandler _instance = new MessageAppendMethodHandler();
private static final Logger _logger = Logger.getLogger(AMQProtocolSession.class);
+ private static MessageAppendMethodHandler _instance = new MessageAppendMethodHandler();
+
public static MessageAppendMethodHandler getInstance()
{
return _instance;
}
private MessageAppendMethodHandler() {}
-
-
- public void methodReceived (AMQStateManager stateManager,
- AMQProtocolSession protocolSession,
- AMQMethodEvent evt)
- throws AMQException
+
+ public void methodReceived (AMQStateManager stateManager, AMQProtocolSession protocolSession, AMQMethodEvent evt) throws AMQException
{
- try {
+ try
+ {
protocolSession.messageAppendBodyReceived((MessageAppendBody)evt.getMethod());
- } catch (Exception e) {
+ }
+ catch (Exception e)
+ {
_logger.error("Unable to add data from MessageAppendBody",e);
}
}
diff --git a/java/client/src/main/java/org/apache/qpid/client/handler/MessageCheckpointMethodHandler.java b/java/client/src/main/java/org/apache/qpid/client/handler/MessageCheckpointMethodHandler.java
index 4c897e33e5..af2844b686 100644
--- a/java/client/src/main/java/org/apache/qpid/client/handler/MessageCheckpointMethodHandler.java
+++ b/java/client/src/main/java/org/apache/qpid/client/handler/MessageCheckpointMethodHandler.java
@@ -21,14 +21,18 @@
package org.apache.qpid.client.handler;
import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.MessageCheckpointBody;
-import org.apache.qpid.protocol.AMQMethodEvent;
import org.apache.qpid.client.protocol.AMQProtocolSession;
import org.apache.qpid.client.state.AMQStateManager;
import org.apache.qpid.client.state.StateAwareMethodListener;
+import org.apache.qpid.framing.MessageCheckpointBody;
+import org.apache.qpid.protocol.AMQMethodEvent;
+
+//import org.apache.log4j.Logger;
public class MessageCheckpointMethodHandler implements StateAwareMethodListener
{
+ //private static final Logger _logger = Logger.getLogger(MessageCheckpointMethodHandler.class);
+
private static MessageCheckpointMethodHandler _instance = new MessageCheckpointMethodHandler();
public static MessageCheckpointMethodHandler getInstance()
@@ -37,12 +41,8 @@ public class MessageCheckpointMethodHandler implements StateAwareMethodListener
}
private MessageCheckpointMethodHandler() {}
-
-
- public void methodReceived (AMQStateManager stateManager,
- AMQProtocolSession protocolSession,
- AMQMethodEvent evt)
- throws AMQException
+
+ public void methodReceived (AMQStateManager stateManager, AMQProtocolSession protocolSession, AMQMethodEvent evt) throws AMQException
{
// TODO
}
diff --git a/java/client/src/main/java/org/apache/qpid/client/handler/MessageCloseMethodHandler.java b/java/client/src/main/java/org/apache/qpid/client/handler/MessageCloseMethodHandler.java
index c7d1c60585..dfe15d3360 100644
--- a/java/client/src/main/java/org/apache/qpid/client/handler/MessageCloseMethodHandler.java
+++ b/java/client/src/main/java/org/apache/qpid/client/handler/MessageCloseMethodHandler.java
@@ -20,18 +20,20 @@
*/
package org.apache.qpid.client.handler;
-import org.apache.log4j.Logger;
import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.MessageCloseBody;
-import org.apache.qpid.protocol.AMQMethodEvent;
import org.apache.qpid.client.protocol.AMQProtocolSession;
import org.apache.qpid.client.state.AMQStateManager;
import org.apache.qpid.client.state.StateAwareMethodListener;
+import org.apache.qpid.framing.MessageCloseBody;
+import org.apache.qpid.protocol.AMQMethodEvent;
+
+import org.apache.log4j.Logger;
public class MessageCloseMethodHandler implements StateAwareMethodListener
{
- private static MessageCloseMethodHandler _instance = new MessageCloseMethodHandler();
private static final Logger _logger = Logger.getLogger(AMQProtocolSession.class);
+
+ private static MessageCloseMethodHandler _instance = new MessageCloseMethodHandler();
public static MessageCloseMethodHandler getInstance()
{
@@ -39,12 +41,8 @@ public class MessageCloseMethodHandler implements StateAwareMethodListener
}
private MessageCloseMethodHandler() {}
-
-
- public void methodReceived (AMQStateManager stateManager,
- AMQProtocolSession protocolSession,
- AMQMethodEvent evt)
- throws AMQException
+
+ public void methodReceived (AMQStateManager stateManager, AMQProtocolSession protocolSession, AMQMethodEvent evt) throws AMQException
{
MessageCloseBody body = (MessageCloseBody)evt.getMethod();
String referenceId = new String(body.getReference());
diff --git a/java/client/src/main/java/org/apache/qpid/client/handler/MessageEmptyMethodHandler.java b/java/client/src/main/java/org/apache/qpid/client/handler/MessageEmptyMethodHandler.java
index 93177cd8ec..1c866d8b44 100644
--- a/java/client/src/main/java/org/apache/qpid/client/handler/MessageEmptyMethodHandler.java
+++ b/java/client/src/main/java/org/apache/qpid/client/handler/MessageEmptyMethodHandler.java
@@ -21,14 +21,18 @@
package org.apache.qpid.client.handler;
import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.MessageEmptyBody;
-import org.apache.qpid.protocol.AMQMethodEvent;
import org.apache.qpid.client.protocol.AMQProtocolSession;
import org.apache.qpid.client.state.AMQStateManager;
import org.apache.qpid.client.state.StateAwareMethodListener;
+import org.apache.qpid.framing.MessageEmptyBody;
+import org.apache.qpid.protocol.AMQMethodEvent;
+
+//import org.apache.log4j.Logger;
public class MessageEmptyMethodHandler implements StateAwareMethodListener
{
+ //private static final Logger _logger = Logger.getLogger(MessageEmptyMethodHandler.class);
+
private static MessageEmptyMethodHandler _instance = new MessageEmptyMethodHandler();
public static MessageEmptyMethodHandler getInstance()
@@ -37,12 +41,8 @@ public class MessageEmptyMethodHandler implements StateAwareMethodListener
}
private MessageEmptyMethodHandler() {}
-
-
- public void methodReceived (AMQStateManager stateManager,
- AMQProtocolSession protocolSession,
- AMQMethodEvent evt)
- throws AMQException
+
+ public void methodReceived (AMQStateManager stateManager, AMQProtocolSession protocolSession, AMQMethodEvent evt) throws AMQException
{
// TODO
}
diff --git a/java/client/src/main/java/org/apache/qpid/client/handler/MessageOffsetMethodHandler.java b/java/client/src/main/java/org/apache/qpid/client/handler/MessageOffsetMethodHandler.java
index 155a6157fa..7371816fb7 100644
--- a/java/client/src/main/java/org/apache/qpid/client/handler/MessageOffsetMethodHandler.java
+++ b/java/client/src/main/java/org/apache/qpid/client/handler/MessageOffsetMethodHandler.java
@@ -21,14 +21,18 @@
package org.apache.qpid.client.handler;
import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.MessageOffsetBody;
-import org.apache.qpid.protocol.AMQMethodEvent;
import org.apache.qpid.client.protocol.AMQProtocolSession;
import org.apache.qpid.client.state.AMQStateManager;
import org.apache.qpid.client.state.StateAwareMethodListener;
+import org.apache.qpid.framing.MessageOffsetBody;
+import org.apache.qpid.protocol.AMQMethodEvent;
+
+//import org.apache.log4j.Logger;
public class MessageOffsetMethodHandler implements StateAwareMethodListener
{
+ //private static final Logger _logger = Logger.getLogger(MessageOffsetMethodHandler.class);
+
private static MessageOffsetMethodHandler _instance = new MessageOffsetMethodHandler();
public static MessageOffsetMethodHandler getInstance()
@@ -36,13 +40,9 @@ public class MessageOffsetMethodHandler implements StateAwareMethodListener
return _instance;
}
- private MessageOffsetMethodHandler() {}
-
-
- public void methodReceived (AMQStateManager stateManager,
- AMQProtocolSession protocolSession,
- AMQMethodEvent evt)
- throws AMQException
+ private MessageOffsetMethodHandler() {}
+
+ public void methodReceived (AMQStateManager stateManager, AMQProtocolSession protocolSession, AMQMethodEvent evt) throws AMQException
{
// TODO
}
diff --git a/java/client/src/main/java/org/apache/qpid/client/handler/MessageOkMethodHandler.java b/java/client/src/main/java/org/apache/qpid/client/handler/MessageOkMethodHandler.java
index 5b392eb599..34214a9178 100644
--- a/java/client/src/main/java/org/apache/qpid/client/handler/MessageOkMethodHandler.java
+++ b/java/client/src/main/java/org/apache/qpid/client/handler/MessageOkMethodHandler.java
@@ -21,14 +21,18 @@
package org.apache.qpid.client.handler;
import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.MessageOkBody;
-import org.apache.qpid.protocol.AMQMethodEvent;
import org.apache.qpid.client.protocol.AMQProtocolSession;
import org.apache.qpid.client.state.AMQStateManager;
import org.apache.qpid.client.state.StateAwareMethodListener;
+import org.apache.qpid.framing.MessageOkBody;
+import org.apache.qpid.protocol.AMQMethodEvent;
+
+//import org.apache.log4j.Logger;
public class MessageOkMethodHandler implements StateAwareMethodListener
{
+ //private static final Logger _logger = Logger.getLogger(MessageOkMethodHandler.class);
+
private static MessageOkMethodHandler _instance = new MessageOkMethodHandler();
public static MessageOkMethodHandler getInstance()
@@ -37,12 +41,8 @@ public class MessageOkMethodHandler implements StateAwareMethodListener
}
private MessageOkMethodHandler() {}
-
-
- public void methodReceived (AMQStateManager stateManager,
- AMQProtocolSession protocolSession,
- AMQMethodEvent evt)
- throws AMQException
+
+ public void methodReceived (AMQStateManager stateManager, AMQProtocolSession protocolSession, AMQMethodEvent evt) throws AMQException
{
// TODO
}
diff --git a/java/client/src/main/java/org/apache/qpid/client/handler/MessageOpenMethodHandler.java b/java/client/src/main/java/org/apache/qpid/client/handler/MessageOpenMethodHandler.java
index 13e05da85a..21bcee9066 100644
--- a/java/client/src/main/java/org/apache/qpid/client/handler/MessageOpenMethodHandler.java
+++ b/java/client/src/main/java/org/apache/qpid/client/handler/MessageOpenMethodHandler.java
@@ -21,14 +21,18 @@
package org.apache.qpid.client.handler;
import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.MessageOpenBody;
-import org.apache.qpid.protocol.AMQMethodEvent;
import org.apache.qpid.client.protocol.AMQProtocolSession;
import org.apache.qpid.client.state.AMQStateManager;
import org.apache.qpid.client.state.StateAwareMethodListener;
+import org.apache.qpid.framing.MessageOpenBody;
+import org.apache.qpid.protocol.AMQMethodEvent;
+
+//import org.apache.log4j.Logger;
public class MessageOpenMethodHandler implements StateAwareMethodListener
{
+ //private static final Logger _logger = Logger.getLogger(MessageOpenMethodHandler.class);
+
private static MessageOpenMethodHandler _instance = new MessageOpenMethodHandler();
public static MessageOpenMethodHandler getInstance()
@@ -37,12 +41,8 @@ public class MessageOpenMethodHandler implements StateAwareMethodListener
}
private MessageOpenMethodHandler() {}
-
-
- public void methodReceived (AMQStateManager stateManager,
- AMQProtocolSession protocolSession,
- AMQMethodEvent evt)
- throws AMQException
+
+ public void methodReceived (AMQStateManager stateManager, AMQProtocolSession protocolSession, AMQMethodEvent evt) throws AMQException
{
// TODO
}
diff --git a/java/client/src/main/java/org/apache/qpid/client/handler/MessageRejectMethodHandler.java b/java/client/src/main/java/org/apache/qpid/client/handler/MessageRejectMethodHandler.java
index 92ad14594c..576e769531 100644
--- a/java/client/src/main/java/org/apache/qpid/client/handler/MessageRejectMethodHandler.java
+++ b/java/client/src/main/java/org/apache/qpid/client/handler/MessageRejectMethodHandler.java
@@ -21,14 +21,18 @@
package org.apache.qpid.client.handler;
import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.MessageRejectBody;
-import org.apache.qpid.protocol.AMQMethodEvent;
import org.apache.qpid.client.protocol.AMQProtocolSession;
import org.apache.qpid.client.state.AMQStateManager;
import org.apache.qpid.client.state.StateAwareMethodListener;
+import org.apache.qpid.framing.MessageRejectBody;
+import org.apache.qpid.protocol.AMQMethodEvent;
+
+//import org.apache.log4j.Logger;
public class MessageRejectMethodHandler implements StateAwareMethodListener
{
+ //private static final Logger _logger = Logger.getLogger(MessageRejectMethodHandler.class);
+
private static MessageRejectMethodHandler _instance = new MessageRejectMethodHandler();
public static MessageRejectMethodHandler getInstance()
@@ -37,12 +41,8 @@ public class MessageRejectMethodHandler implements StateAwareMethodListener
}
private MessageRejectMethodHandler() {}
-
-
- public void methodReceived (AMQStateManager stateManager,
- AMQProtocolSession protocolSession,
- AMQMethodEvent evt)
- throws AMQException
+
+ public void methodReceived (AMQStateManager stateManager, AMQProtocolSession protocolSession, AMQMethodEvent evt) throws AMQException
{
// TODO
}
diff --git a/java/client/src/main/java/org/apache/qpid/client/handler/MessageResumeMethodHandler.java b/java/client/src/main/java/org/apache/qpid/client/handler/MessageResumeMethodHandler.java
index 691dd488ff..f670ca5b5a 100644
--- a/java/client/src/main/java/org/apache/qpid/client/handler/MessageResumeMethodHandler.java
+++ b/java/client/src/main/java/org/apache/qpid/client/handler/MessageResumeMethodHandler.java
@@ -21,14 +21,18 @@
package org.apache.qpid.client.handler;
import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.MessageResumeBody;
-import org.apache.qpid.protocol.AMQMethodEvent;
import org.apache.qpid.client.protocol.AMQProtocolSession;
import org.apache.qpid.client.state.AMQStateManager;
import org.apache.qpid.client.state.StateAwareMethodListener;
+import org.apache.qpid.framing.MessageResumeBody;
+import org.apache.qpid.protocol.AMQMethodEvent;
+
+//import org.apache.log4j.Logger;
public class MessageResumeMethodHandler implements StateAwareMethodListener
{
+ //private static final Logger _logger = Logger.getLogger(MessageResumeMethodHandler.class);
+
private static MessageResumeMethodHandler _instance = new MessageResumeMethodHandler();
public static MessageResumeMethodHandler getInstance()
@@ -37,14 +41,10 @@ public class MessageResumeMethodHandler implements StateAwareMethodListener
}
private MessageResumeMethodHandler() {}
-
-
- public void methodReceived (AMQStateManager stateManager,
- AMQProtocolSession protocolSession,
- AMQMethodEvent evt)
- throws AMQException
+
+ public void methodReceived (AMQStateManager stateManager, AMQProtocolSession protocolSession, AMQMethodEvent evt) throws AMQException
{
- System.out.println("");
+ // TODO
}
}
diff --git a/java/client/src/main/java/org/apache/qpid/client/handler/MessageTransferMethodHandler.java b/java/client/src/main/java/org/apache/qpid/client/handler/MessageTransferMethodHandler.java
index f278fb5116..d16f0c1fc4 100644
--- a/java/client/src/main/java/org/apache/qpid/client/handler/MessageTransferMethodHandler.java
+++ b/java/client/src/main/java/org/apache/qpid/client/handler/MessageTransferMethodHandler.java
@@ -20,7 +20,6 @@
*/
package org.apache.qpid.client.handler;
-import org.apache.log4j.Logger;
import org.apache.qpid.AMQException;
import org.apache.qpid.client.message.MessageHeaders;
import org.apache.qpid.client.message.UnprocessedMessage;
@@ -31,10 +30,13 @@ import org.apache.qpid.framing.Content;
import org.apache.qpid.framing.MessageTransferBody;
import org.apache.qpid.protocol.AMQMethodEvent;
+import org.apache.log4j.Logger;
+
public class MessageTransferMethodHandler implements StateAwareMethodListener
{
- private static MessageTransferMethodHandler _instance = new MessageTransferMethodHandler();
private static final Logger _logger = Logger.getLogger(MessageTransferMethodHandler.class);
+
+ private static MessageTransferMethodHandler _instance = new MessageTransferMethodHandler();
public static MessageTransferMethodHandler getInstance()
{
@@ -42,18 +44,11 @@ public class MessageTransferMethodHandler implements StateAwareMethodListener
}
private MessageTransferMethodHandler() {}
-
-
- public void methodReceived (AMQStateManager stateManager,
- AMQProtocolSession protocolSession,
- AMQMethodEvent evt)
- throws AMQException
+
+ public void methodReceived (AMQStateManager stateManager, AMQProtocolSession protocolSession, AMQMethodEvent evt) throws AMQException
{
- final UnprocessedMessage msg = new UnprocessedMessage();
MessageTransferBody transferBody = (MessageTransferBody) evt.getMethod();
- msg.channelId = evt.getChannelId();
- msg.deliveryTag = evt.getRequestId();
_logger.debug("New JmsDeliver method received");
MessageHeaders messageHeaders = new MessageHeaders();
@@ -73,7 +68,7 @@ public class MessageTransferMethodHandler implements StateAwareMethodListener
messageHeaders.setDeliveryMode(transferBody.getDeliveryMode());
messageHeaders.setJMSHeaders(transferBody.getApplicationHeaders());
- msg.contentHeader = messageHeaders;
+ final UnprocessedMessage msg = new UnprocessedMessage(evt.getChannelId(), evt.getRequestId(), messageHeaders);
if(transferBody.getBody().getContentType() == Content.TypeEnum.INLINE_T)
{
diff --git a/java/client/src/main/java/org/apache/qpid/client/handler/QueueDeleteOkMethodHandler.java b/java/client/src/main/java/org/apache/qpid/client/handler/QueueDeleteOkMethodHandler.java
index b8b75accb4..d2618960dd 100644
--- a/java/client/src/main/java/org/apache/qpid/client/handler/QueueDeleteOkMethodHandler.java
+++ b/java/client/src/main/java/org/apache/qpid/client/handler/QueueDeleteOkMethodHandler.java
@@ -17,38 +17,35 @@
*/
package org.apache.qpid.client.handler;
+import org.apache.qpid.AMQException;
import org.apache.qpid.client.protocol.AMQProtocolSession;
-import org.apache.qpid.client.state.StateAwareMethodListener;
import org.apache.qpid.client.state.AMQStateManager;
-import org.apache.qpid.AMQException;
+import org.apache.qpid.client.state.StateAwareMethodListener;
import org.apache.qpid.framing.QueueDeleteOkBody;
import org.apache.qpid.protocol.AMQMethodEvent;
+
import org.apache.log4j.Logger;
-/**
- * @author Apache Software Foundation
- */
public class QueueDeleteOkMethodHandler implements StateAwareMethodListener
{
- private static final Logger _logger = Logger.getLogger(QueueDeleteOkMethodHandler.class);
- private static final QueueDeleteOkMethodHandler _instance = new QueueDeleteOkMethodHandler();
-
- public static QueueDeleteOkMethodHandler getInstance()
- {
- return _instance;
- }
-
- private QueueDeleteOkMethodHandler()
- {
- }
-
- public void methodReceived(AMQStateManager stateManager, AMQProtocolSession protocolSession, AMQMethodEvent evt) throws AMQException
- {
- if (_logger.isDebugEnabled())
- {
+ private static final Logger _logger = Logger.getLogger(QueueDeleteOkMethodHandler.class);
+
+ private static final QueueDeleteOkMethodHandler _instance = new QueueDeleteOkMethodHandler();
+
+ public static QueueDeleteOkMethodHandler getInstance()
+ {
+ return _instance;
+ }
+
+ private QueueDeleteOkMethodHandler() {}
+
+ public void methodReceived(AMQStateManager stateManager, AMQProtocolSession protocolSession, AMQMethodEvent evt) throws AMQException
+ {
+ if (_logger.isDebugEnabled())
+ {
QueueDeleteOkBody body = (QueueDeleteOkBody) evt.getMethod();
_logger.debug("Received Queue.Delete-Ok message, message count: " + body.messageCount);
- }
- }
+ }
+ }
}
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/AbstractBytesMessage.java b/java/client/src/main/java/org/apache/qpid/client/message/AbstractBytesMessage.java
index f27436393b..1afd3fdd40 100644
--- a/java/client/src/main/java/org/apache/qpid/client/message/AbstractBytesMessage.java
+++ b/java/client/src/main/java/org/apache/qpid/client/message/AbstractBytesMessage.java
@@ -22,6 +22,7 @@ package org.apache.qpid.client.message;
import java.io.IOException;
import java.nio.charset.Charset;
+import org.apache.qpid.framing.AMQShortString;
import javax.jms.JMSException;
import javax.jms.MessageEOFException;
@@ -54,7 +55,7 @@ public abstract class AbstractBytesMessage extends AbstractJMSMessage
AbstractBytesMessage(ByteBuffer data)
{
super(data); // this instanties a content header
- getMessageHeaders().setContentType(getMimeType());
+ getMessageHeaders().setContentType(getMimeTypeAsShortString());
if (_data == null)
{
@@ -68,13 +69,12 @@ public abstract class AbstractBytesMessage extends AbstractJMSMessage
_data.setAutoExpand(true);
}
-
AbstractBytesMessage(long messageNbr, MessageHeaders contentHeader, ByteBuffer data)
throws AMQException
{
// TODO: this casting is ugly. Need to review whole ContentHeaderBody idea
super(messageNbr, contentHeader, data);
- getMessageHeaders().setContentType(getMimeType());
+ getMessageHeaders().setContentType(getMimeTypeAsShortString());
}
public void clearBodyImpl() throws JMSException
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/AbstractBytesTypedMessage.java b/java/client/src/main/java/org/apache/qpid/client/message/AbstractBytesTypedMessage.java
index 7b97a8b065..c806a93015 100644
--- a/java/client/src/main/java/org/apache/qpid/client/message/AbstractBytesTypedMessage.java
+++ b/java/client/src/main/java/org/apache/qpid/client/message/AbstractBytesTypedMessage.java
@@ -10,6 +10,7 @@ import javax.jms.MessageNotReadableException;
import javax.jms.MessageNotWriteableException;
import org.apache.mina.common.ByteBuffer;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.AMQException;
/**
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/AbstractJMSMessage.java b/java/client/src/main/java/org/apache/qpid/client/message/AbstractJMSMessage.java
index 2de86b2cb3..6b55e5237b 100644
--- a/java/client/src/main/java/org/apache/qpid/client/message/AbstractJMSMessage.java
+++ b/java/client/src/main/java/org/apache/qpid/client/message/AbstractJMSMessage.java
@@ -34,15 +34,22 @@ import org.apache.mina.common.ByteBuffer;
import org.apache.qpid.AMQException;
import org.apache.qpid.client.AMQDestination;
import org.apache.qpid.client.BasicMessageConsumer;
-import org.apache.qpid.client.CustomJMXProperty;
+import org.apache.qpid.client.CustomJMSXProperty;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.framing.FieldTable;
import org.apache.qpid.url.AMQBindingURL;
import org.apache.qpid.url.BindingURL;
import org.apache.qpid.url.URLSyntaxException;
+import javax.jms.*;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.Map;
+
public abstract class AbstractJMSMessage extends AMQMessage implements org.apache.qpid.jms.Message
{
private static final Map _destinationCache = Collections.synchronizedMap(new ReferenceMap());
+
protected boolean _redelivered;
@@ -51,6 +58,7 @@ public abstract class AbstractJMSMessage extends AMQMessage implements org.apach
protected boolean _readableMessage = false;
protected boolean _changedData;
private Destination _destination;
+ private JMSHeaderAdapter _headerAdapter;
private BasicMessageConsumer _consumer;
protected AbstractJMSMessage(ByteBuffer data)
@@ -84,17 +92,29 @@ public abstract class AbstractJMSMessage extends AMQMessage implements org.apach
_readableProperties = (_messageHeaders != null);
}
- public String getJMSMessageID() throws JMSException
+ public AMQShortString getJMSMessageIDAsShortString() throws JMSException
{
if (getMessageHeaders().getMessageId() == null)
{
- getMessageHeaders().setMessageId("ID:" + _deliveryTag);
+ getMessageHeaders().setMessageId(new AMQShortString("ID:" + _deliveryTag));
}
return getMessageHeaders().getMessageId();
}
+
+ // The String version is required for javax.jms.Message
+ public String getJMSMessageID() throws JMSException
+ {
+ return getJMSMessageIDAsShortString().asString();
+ }
+ // The String version is required for javax.jms.Message
public void setJMSMessageID(String messageId) throws JMSException
{
+ setJMSMessageID(new AMQShortString(messageId));
+ }
+
+ public void setJMSMessageID(AMQShortString messageId) throws JMSException
+ {
getMessageHeaders().setMessageId(messageId);
}
@@ -115,22 +135,35 @@ public abstract class AbstractJMSMessage extends AMQMessage implements org.apach
public void setJMSCorrelationIDAsBytes(byte[] bytes) throws JMSException
{
- getMessageHeaders().setCorrelationId(new String(bytes));
+ getMessageHeaders().setCorrelationId(new AMQShortString(bytes));
}
+ // The String version is required for javax.jms.Message
public void setJMSCorrelationID(String correlationId) throws JMSException
{
+ setJMSCorrelationID(new AMQShortString(correlationId));
+ }
+
+ public void setJMSCorrelationID(AMQShortString correlationId) throws JMSException
+ {
getMessageHeaders().setCorrelationId(correlationId);
}
- public String getJMSCorrelationID() throws JMSException
+ public AMQShortString getJMSCorrelationIDAsShortString() throws JMSException
{
return getMessageHeaders().getCorrelationId();
}
+ // The String version is required for javax.jms.Message
+ public String getJMSCorrelationID() throws JMSException
+ {
+ AMQShortString ss = getMessageHeaders().getCorrelationId();
+ return ss == null ? null : ss.asString();
+ }
+
public Destination getJMSReplyTo() throws JMSException
{
- String replyToEncoding = getMessageHeaders().getReplyTo();
+ AMQShortString replyToEncoding = getMessageHeaders().getReplyTo();
if (replyToEncoding == null)
{
return null;
@@ -142,7 +175,7 @@ public abstract class AbstractJMSMessage extends AMQMessage implements org.apach
{
try
{
- BindingURL binding = new AMQBindingURL(replyToEncoding);
+ BindingURL binding = new AMQBindingURL(replyToEncoding.asString());
dest = AMQDestination.createDestination(binding);
}
catch (URLSyntaxException e)
@@ -165,11 +198,11 @@ public abstract class AbstractJMSMessage extends AMQMessage implements org.apach
if (!(destination instanceof AMQDestination))
{
throw new IllegalArgumentException("ReplyTo destination may only be an AMQDestination - passed argument was type " +
- destination.getClass());
+ destination.getClass());
}
final AMQDestination amqd = (AMQDestination) destination;
- final String encodedDestination = amqd.getEncodedName();
+ final AMQShortString encodedDestination = amqd.getEncodedName();
_destinationCache.put(encodedDestination, destination);
getMessageHeaders().setReplyTo(encodedDestination);
}
@@ -179,7 +212,7 @@ public abstract class AbstractJMSMessage extends AMQMessage implements org.apach
return _destination;
}
- public void setJMSDestination(Destination destination) throws JMSException
+ public void setJMSDestination(Destination destination)
{
_destination = destination;
}
@@ -209,7 +242,7 @@ public abstract class AbstractJMSMessage extends AMQMessage implements org.apach
// Since the type field is not a part of message.transport and is used only for
// JMS messages, this change to JMS Headers solves the problem.
// return getMessageHeaders().getType();
- return getStringProperty(CustomJMXProperty.JMSXType.toString());
+ return getStringProperty(CustomJMSXProperty.JMSXType.toString());
}
public void setJMSType(String string) throws JMSException
@@ -217,7 +250,7 @@ public abstract class AbstractJMSMessage extends AMQMessage implements org.apach
// Since the type field is not a part of message.transport and is used only for
// JMS messages, this change to JMS Headers solves the problem.
// getMessageHeaders().setType(string);
- setStringProperty(CustomJMXProperty.JMSXType.toString(), string);
+ setStringProperty(CustomJMSXProperty.JMSXType.toString(), string);
}
public long getJMSExpiration() throws JMSException
@@ -243,7 +276,6 @@ public abstract class AbstractJMSMessage extends AMQMessage implements org.apach
public void clearProperties() throws JMSException
{
getMessageHeaders().getJMSHeaders().clear();
-
_readableProperties = false;
}
@@ -253,11 +285,24 @@ public abstract class AbstractJMSMessage extends AMQMessage implements org.apach
_readableMessage = false;
}
+ public boolean propertyExists(AMQShortString propertyName) throws JMSException
+ {
+ checkPropertyName(propertyName);
+ return getMessageHeaders().getJMSHeaders().propertyExists(propertyName);
+ }
public boolean propertyExists(String propertyName) throws JMSException
{
+ return propertyExists(new AMQShortString(propertyName));
+ }
+
+ public boolean getBooleanProperty(AMQShortString propertyName) throws JMSException
+ {
checkPropertyName(propertyName);
- return getMessageHeaders().getJMSHeaders().propertyExists(propertyName);
+ Boolean b = getMessageHeaders().getJMSHeaders().getBoolean(propertyName);
+ if (b != null)
+ return b;
+ return false;
}
public boolean getBooleanProperty(String propertyName) throws JMSException
@@ -267,7 +312,6 @@ public abstract class AbstractJMSMessage extends AMQMessage implements org.apach
if (b != null)
return b;
return false;
-// return getMessageHeaders().getJMSHeaders().getBoolean(propertyName);
}
public byte getByteProperty(String propertyName) throws JMSException
@@ -277,7 +321,13 @@ public abstract class AbstractJMSMessage extends AMQMessage implements org.apach
if (b == null)
throw new NumberFormatException("Byte value null");
return b;
-// return getMessageHeaders().getJMSHeaders().getByte(propertyName);
+ }
+
+ public byte[] getBytesProperty(AMQShortString propertyName) throws JMSException
+ {
+ checkPropertyName(propertyName);
+ return getMessageHeaders().getJMSHeaders().getBytes(propertyName);
+
}
public short getShortProperty(String propertyName) throws JMSException
@@ -291,7 +341,6 @@ public abstract class AbstractJMSMessage extends AMQMessage implements org.apach
if (b == null)
throw new NumberFormatException("Short value null");
return (short)b;
-// return getMessageHeaders().getJMSHeaders().getShort(propertyName);
}
public int getIntProperty(String propertyName) throws JMSException
@@ -309,7 +358,6 @@ public abstract class AbstractJMSMessage extends AMQMessage implements org.apach
if (b == null)
throw new NumberFormatException("Int value null");
return (short)b;
-// return getMessageHeaders().getJMSHeaders().getInteger(propertyName);
}
public long getLongProperty(String propertyName) throws JMSException
@@ -318,6 +366,7 @@ public abstract class AbstractJMSMessage extends AMQMessage implements org.apach
Long l = getMessageHeaders().getJMSHeaders().getLong(propertyName);
if (l != null)
return l;
+ // try Integer
Integer i = getMessageHeaders().getJMSHeaders().getInteger(propertyName);
if (i != null)
return i;
@@ -330,7 +379,6 @@ public abstract class AbstractJMSMessage extends AMQMessage implements org.apach
if (b == null)
throw new NumberFormatException("Long value null");
return (short)b;
-// return getMessageHeaders().getJMSHeaders().getLong(propertyName);
}
public float getFloatProperty(String propertyName) throws JMSException
@@ -374,13 +422,18 @@ public abstract class AbstractJMSMessage extends AMQMessage implements org.apach
return getMessageHeaders().getJMSHeaders().getPropertyNames();
}
- public void setBooleanProperty(String propertyName, boolean b) throws JMSException
+ public void setBooleanProperty(AMQShortString propertyName, boolean b) throws JMSException
{
checkWritableProperties();
checkPropertyName(propertyName);
getMessageHeaders().getJMSHeaders().setBoolean(propertyName, b);
}
+ public void setBooleanProperty(String propertyName, boolean b) throws JMSException
+ {
+ setBooleanProperty(new AMQShortString(propertyName), b);
+ }
+
public void setByteProperty(String propertyName, byte b) throws JMSException
{
checkWritableProperties();
@@ -437,7 +490,7 @@ public abstract class AbstractJMSMessage extends AMQMessage implements org.apach
getMessageHeaders().getJMSHeaders().setObject(propertyName, object);
}
- protected void removeProperty(String propertyName) throws JMSException
+ protected void removeProperty(AMQShortString propertyName) throws JMSException
{
checkPropertyName(propertyName);
getMessageHeaders().getJMSHeaders().remove(propertyName);
@@ -468,7 +521,7 @@ public abstract class AbstractJMSMessage extends AMQMessage implements org.apach
public void acknowledge() throws JMSException
{
- if(_session != null)
+ if (_session != null)
{
_session.acknowledge();
}
@@ -488,7 +541,12 @@ public abstract class AbstractJMSMessage extends AMQMessage implements org.apach
*/
public abstract String toBodyString() throws JMSException;
- public abstract String getMimeType();
+ public String getMimeType()
+ {
+ return getMimeTypeAsShortString().toString();
+ }
+
+ public abstract AMQShortString getMimeTypeAsShortString();
public String toString()
{
@@ -496,6 +554,7 @@ public abstract class AbstractJMSMessage extends AMQMessage implements org.apach
{
StringBuffer buf = new StringBuffer("Body:\n");
buf.append(toBodyString());
+ buf.append("\nJMS Correlation ID: ").append(getJMSCorrelationID());
buf.append("\nJMS timestamp: ").append(getJMSTimestamp());
buf.append("\nJMS expiration: ").append(getJMSExpiration());
buf.append("\nJMS priority: ").append(getJMSPriority());
@@ -525,13 +584,13 @@ public abstract class AbstractJMSMessage extends AMQMessage implements org.apach
getMessageHeaders().setJMSHeaders(messageProperties);
}
- private void checkPropertyName(String propertyName)
+ private void checkPropertyName(CharSequence propertyName)
{
if (propertyName == null)
{
throw new IllegalArgumentException("Property name must not be null");
}
- else if ("".equals(propertyName))
+ else if (propertyName.length() == 0)
{
throw new IllegalArgumentException("Property name must not be the empty string");
}
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/AbstractJMSMessageFactory.java b/java/client/src/main/java/org/apache/qpid/client/message/AbstractJMSMessageFactory.java
index 73901c5cf2..b0b45478a3 100644
--- a/java/client/src/main/java/org/apache/qpid/client/message/AbstractJMSMessageFactory.java
+++ b/java/client/src/main/java/org/apache/qpid/client/message/AbstractJMSMessageFactory.java
@@ -20,6 +20,9 @@
*/
package org.apache.qpid.client.message;
+import org.apache.qpid.AMQException;
+import org.apache.qpid.framing.AMQShortString;
+
import java.util.Iterator;
import java.util.List;
@@ -27,7 +30,6 @@ import javax.jms.JMSException;
import org.apache.log4j.Logger;
import org.apache.mina.common.ByteBuffer;
-import org.apache.qpid.AMQException;
public abstract class AbstractJMSMessageFactory implements MessageFactory
{
@@ -61,5 +63,4 @@ public abstract class AbstractJMSMessageFactory implements MessageFactory
msg.setJMSRedelivered(redelivered);
return msg;
}
-
}
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/JMSBytesMessage.java b/java/client/src/main/java/org/apache/qpid/client/message/JMSBytesMessage.java
index 6943f277ca..9f0d51e9e4 100644
--- a/java/client/src/main/java/org/apache/qpid/client/message/JMSBytesMessage.java
+++ b/java/client/src/main/java/org/apache/qpid/client/message/JMSBytesMessage.java
@@ -25,6 +25,7 @@ import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
+import org.apache.qpid.framing.AMQShortString;
import javax.jms.BytesMessage;
import javax.jms.JMSException;
@@ -35,9 +36,11 @@ import org.apache.qpid.AMQException;
public class JMSBytesMessage extends AbstractBytesMessage implements BytesMessage
{
- private static final String MIME_TYPE = "application/octet-stream";
+ public static final String MIME_TYPE = "application/octet-stream";
+ private static final AMQShortString MIME_TYPE_SHORT_STRING = new AMQShortString(MIME_TYPE);
- JMSBytesMessage()
+
+ public JMSBytesMessage()
{
this(null);
}
@@ -65,9 +68,9 @@ public class JMSBytesMessage extends AbstractBytesMessage implements BytesMessag
_readableMessage = true;
}
- public String getMimeType()
+ public AMQShortString getMimeTypeAsShortString()
{
- return MIME_TYPE;
+ return MIME_TYPE_SHORT_STRING;
}
public long getBodyLength() throws JMSException
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/JMSBytesMessageFactory.java b/java/client/src/main/java/org/apache/qpid/client/message/JMSBytesMessageFactory.java
index ed8586a06b..2045d571b7 100644
--- a/java/client/src/main/java/org/apache/qpid/client/message/JMSBytesMessageFactory.java
+++ b/java/client/src/main/java/org/apache/qpid/client/message/JMSBytesMessageFactory.java
@@ -24,6 +24,7 @@ import javax.jms.JMSException;
import org.apache.mina.common.ByteBuffer;
import org.apache.qpid.AMQException;
+import org.apache.qpid.framing.AMQShortString;
public class JMSBytesMessageFactory extends AbstractJMSMessageFactory
{
diff --git a/java/common/src/main/java/org/apache/qpid/framing/JMSPropertyFieldTable.java b/java/client/src/main/java/org/apache/qpid/client/message/JMSHeaderAdapter.java
index d78034cf2f..3086e5b90a 100644
--- a/java/common/src/main/java/org/apache/qpid/framing/JMSPropertyFieldTable.java
+++ b/java/client/src/main/java/org/apache/qpid/client/message/JMSHeaderAdapter.java
@@ -1,453 +1,527 @@
-/*
- * 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.framing;
-
-import org.apache.mina.common.ByteBuffer;
-import org.apache.qpid.AMQPInvalidClassException;
-
-import javax.jms.MessageFormatException;
-import javax.jms.JMSException;
-import java.util.Enumeration;
-
-
-public class JMSPropertyFieldTable
-{
- private FieldTable _fieldtable;
-
- public JMSPropertyFieldTable(FieldTable table)
- {
- _fieldtable = table;
- }
-
-
- private void checkPropertyName(String propertyName)
- {
- if (propertyName == null)
- {
- throw new IllegalArgumentException("Property name must not be null");
- }
- else if ("".equals(propertyName))
- {
- throw new IllegalArgumentException("Property name must not be the empty string");
- }
-
- checkIdentiferFormat(propertyName);
- }
-
- protected static void checkIdentiferFormat(String propertyName)
- {
-// JMS requirements 3.5.1 Property Names
-// Identifiers:
-// - An identifier is an unlimited-length character sequence that must begin
-// with a Java identifier start character; all following characters must be Java
-// identifier part characters. An identifier start character is any character for
-// which the method Character.isJavaIdentifierStart returns true. This includes
-// '_' and '$'. An identifier part character is any character for which the
-// method Character.isJavaIdentifierPart returns true.
-// - Identifiers cannot be the names NULL, TRUE, or FALSE.
-// – Identifiers cannot be NOT, AND, OR, BETWEEN, LIKE, IN, IS, or
-// ESCAPE.
-// – Identifiers are either header field references or property references. The
-// type of a property value in a message selector corresponds to the type
-// used to set the property. If a property that does not exist in a message is
-// referenced, its value is NULL. The semantics of evaluating NULL values
-// in a selector are described in Section 3.8.1.2, “Null Values.”
-// – The conversions that apply to the get methods for properties do not
-// apply when a property is used in a message selector expression. For
-// example, suppose you set a property as a string value, as in the
-// following:
-// myMessage.setStringProperty("NumberOfOrders", "2");
-// The following expression in a message selector would evaluate to false,
-// because a string cannot be used in an arithmetic expression:
-// "NumberOfOrders > 1"
-// – Identifiers are case sensitive.
-// – Message header field references are restricted to JMSDeliveryMode,
-// JMSPriority, JMSMessageID, JMSTimestamp, JMSCorrelationID, and
-// JMSType. JMSMessageID, JMSCorrelationID, and JMSType values may be
-// null and if so are treated as a NULL value.
-
- if (Boolean.getBoolean("strict-jms"))
- {
- // JMS start character
- if (!(Character.isJavaIdentifierStart(propertyName.charAt(0))))
- {
- throw new IllegalArgumentException("Identifier '" + propertyName + "' does not start with a valid JMS identifier start character");
- }
-
- // JMS part character
- int length = propertyName.length();
- for (int c = 1; c < length; c++)
- {
- if (!(Character.isJavaIdentifierPart(propertyName.charAt(c))))
- {
- throw new IllegalArgumentException("Identifier '" + propertyName + "' contains an invalid JMS identifier character");
- }
- }
-
- // JMS invalid names
- if ((propertyName.equals("NULL")
- || propertyName.equals("TRUE")
- || propertyName.equals("FALSE")
- || propertyName.equals("NOT")
- || propertyName.equals("AND")
- || propertyName.equals("OR")
- || propertyName.equals("BETWEEN")
- || propertyName.equals("LIKE")
- || propertyName.equals("IN")
- || propertyName.equals("IS")
- || propertyName.equals("ESCAPE")))
- {
- throw new IllegalArgumentException("Identifier '" + propertyName + "' is not allowed in JMS");
- }
- }
-
- }
-
- // MapMessage Interface
- public boolean getBoolean(String string) throws JMSException
- {
- Boolean b = _fieldtable.getBoolean(string);
-
- if (b == null)
- {
- if (_fieldtable.containsKey(string))
- {
- Object str = _fieldtable.getObject(string);
-
- if (str == null || !(str instanceof String))
- {
- throw new MessageFormatException("getBoolean can't use " + string + " item.");
- }
- else
- {
- return Boolean.valueOf((String) str);
- }
- }
- else
- {
- b = Boolean.valueOf(null);
- }
- }
-
- return b;
- }
-
- public char getCharacter(String string) throws JMSException
- {
- Character c = _fieldtable.getCharacter(string);
-
- if (c == null)
- {
- if (_fieldtable.isNullStringValue(string))
- {
- throw new NullPointerException("Cannot convert null char");
- }
- else
- {
- throw new MessageFormatException("getChar can't use " + string + " item.");
- }
- }
- else
- {
- return (char) c;
- }
- }
-
- public byte[] getBytes(String string) throws JMSException
- {
- byte[] bs = _fieldtable.getBytes(string);
-
- if (bs == null)
- {
- throw new MessageFormatException("getBytes can't use " + string + " item.");
- }
- else
- {
- return bs;
- }
- }
-
- public byte getByte(String string) throws JMSException
- {
- Byte b = _fieldtable.getByte(string);
- if (b == null)
- {
- if (_fieldtable.containsKey(string))
- {
- Object str = _fieldtable.getObject(string);
-
- if (str == null || !(str instanceof String))
- {
- throw new MessageFormatException("getByte can't use " + string + " item.");
- }
- else
- {
- return Byte.valueOf((String) str);
- }
- }
- else
- {
- b = Byte.valueOf(null);
- }
- }
-
- return b;
- }
-
- public short getShort(String string) throws JMSException
- {
- Short s = _fieldtable.getShort(string);
-
- if (s == null)
- {
- s = Short.valueOf(getByte(string));
- }
-
- return s;
- }
-
- public int getInteger(String string) throws JMSException
- {
- Integer i = _fieldtable.getInteger(string);
-
- if (i == null)
- {
- i = Integer.valueOf(getShort(string));
- }
-
- return i;
- }
-
- public long getLong(String string) throws JMSException
- {
- Long l = _fieldtable.getLong(string);
-
- if (l == null)
- {
- l = Long.valueOf(getInteger(string));
- }
-
- return l;
- }
-
- public float getFloat(String string) throws JMSException
- {
- Float f = _fieldtable.getFloat(string);
-
- if (f == null)
- {
- if (_fieldtable.containsKey(string))
- {
- Object str = _fieldtable.getObject(string);
-
- if (str == null || !(str instanceof String))
- {
- throw new MessageFormatException("getFloat can't use " + string + " item.");
- }
- else
- {
- return Float.valueOf((String) str);
- }
- }
- else
- {
- f = Float.valueOf(null);
- }
-
- }
-
- return f;
- }
-
- public double getDouble(String string) throws JMSException
- {
- Double d = _fieldtable.getDouble(string);
-
- if (d == null)
- {
- d = Double.valueOf(getFloat(string));
- }
-
- return d;
- }
-
- public String getString(String string) throws JMSException
- {
- String s = _fieldtable.getString(string);
-
- if (s == null)
- {
- if (_fieldtable.containsKey(string))
- {
- Object o = _fieldtable.getObject(string);
- if (o instanceof byte[])
- {
- throw new MessageFormatException("getObject couldn't find " + string + " item.");
- }
- else
- {
- if (o == null)
- {
- return null;
- }
- else
- {
- s = String.valueOf(o);
- }
- }
- }
- }
-
- return s;
- }
-
- public Object getObject(String string) throws JMSException
- {
- return _fieldtable.getObject(string);
- }
-
- public void setBoolean(String string, boolean b) throws JMSException
- {
- checkPropertyName(string);
- _fieldtable.setBoolean(string, b);
- }
-
- public void setChar(String string, char c) throws JMSException
- {
- checkPropertyName(string);
- _fieldtable.setChar(string, c);
- }
-
- public Object setBytes(String string, byte[] bytes)
- {
- return _fieldtable.setBytes(string, bytes, 0, bytes.length);
- }
-
- public Object setBytes(String string, byte[] bytes, int start, int length)
- {
- return _fieldtable.setBytes(string, bytes, start, length);
- }
-
- public void setByte(String string, byte b) throws JMSException
- {
- checkPropertyName(string);
- _fieldtable.setByte(string, b);
- }
-
- public void setShort(String string, short i) throws JMSException
- {
- checkPropertyName(string);
- _fieldtable.setShort(string, i);
- }
-
- public void setInteger(String string, int i) throws JMSException
- {
- checkPropertyName(string);
- _fieldtable.setInteger(string, i);
- }
-
- public void setLong(String string, long l) throws JMSException
- {
- checkPropertyName(string);
- _fieldtable.setLong(string, l);
- }
-
- public void setFloat(String string, float v) throws JMSException
- {
- checkPropertyName(string);
- _fieldtable.setFloat(string, v);
- }
-
- public void setDouble(String string, double v) throws JMSException
- {
- checkPropertyName(string);
- _fieldtable.setDouble(string, v);
- }
-
- public void setString(String string, String string1) throws JMSException
- {
- checkPropertyName(string);
- _fieldtable.setString(string, string1);
- }
-
- public void setObject(String string, Object object) throws JMSException
- {
- checkPropertyName(string);
- try
- {
- _fieldtable.setObject(string, object);
- }
- catch (AMQPInvalidClassException aice)
- {
- throw new MessageFormatException("Only primatives are allowed object is:" + object.getClass());
- }
- }
-
- public boolean itemExists(String string) throws JMSException
- {
- return _fieldtable.containsKey(string);
- }
-
- public void setFieldTable(FieldTable headers)
- {
- _fieldtable = headers;
- }
-
- public Enumeration getPropertyNames()
- {
- return _fieldtable.getPropertyNames();
- }
-
- public void clear()
- {
- _fieldtable.clear();
- }
-
- public boolean propertyExists(String propertyName)
- {
- return _fieldtable.propertyExists(propertyName);
- }
-
- public Object put(Object key, Object value)
- {
- return _fieldtable.put(key, value);
- }
-
- public Object remove(String propertyName)
- {
- return _fieldtable.remove(propertyName);
- }
-
- public boolean isEmpty()
- {
- return _fieldtable.isEmpty();
- }
-
- public void writeToBuffer(ByteBuffer data)
- {
- _fieldtable.writeToBuffer(data);
- }
-
- public Enumeration getMapNames()
- {
- return getPropertyNames();
- }
-}
+/*
+ *
+ * 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.client.message;
+
+import org.apache.qpid.framing.FieldTable;
+import org.apache.qpid.framing.AMQShortString;
+import org.apache.qpid.AMQPInvalidClassException;
+import org.apache.mina.common.ByteBuffer;
+
+import javax.jms.JMSException;
+import javax.jms.MessageFormatException;
+import java.util.Enumeration;
+
+
+public final class JMSHeaderAdapter
+{
+ private final FieldTable _headers;
+
+ public JMSHeaderAdapter(FieldTable headers)
+ {
+ _headers = headers;
+ }
+
+
+ public FieldTable getHeaders()
+ {
+ return _headers;
+ }
+
+ public boolean getBoolean(String string) throws JMSException
+ {
+ Boolean b = getHeaders().getBoolean(string);
+
+ if (b == null)
+ {
+ if (getHeaders().containsKey(string))
+ {
+ Object str = getHeaders().getObject(string);
+
+ if (str == null || !(str instanceof String))
+ {
+ throw new MessageFormatException("getBoolean can't use " + string + " item.");
+ }
+ else
+ {
+ return Boolean.valueOf((String) str);
+ }
+ }
+ else
+ {
+ b = Boolean.valueOf(null);
+ }
+ }
+
+ return b;
+ }
+
+ public boolean getBoolean(AMQShortString string) throws JMSException
+ {
+ Boolean b = getHeaders().getBoolean(string);
+
+ if (b == null)
+ {
+ if (getHeaders().containsKey(string))
+ {
+ Object str = getHeaders().getObject(string);
+
+ if (str == null || !(str instanceof String))
+ {
+ throw new MessageFormatException("getBoolean can't use " + string + " item.");
+ }
+ else
+ {
+ return Boolean.valueOf((String) str);
+ }
+ }
+ else
+ {
+ b = Boolean.valueOf(null);
+ }
+ }
+
+ return b;
+ }
+
+ public char getCharacter(String string) throws JMSException
+ {
+ Character c = getHeaders().getCharacter(string);
+
+ if (c == null)
+ {
+ if (getHeaders().isNullStringValue(string))
+ {
+ throw new NullPointerException("Cannot convert null char");
+ }
+ else
+ {
+ throw new MessageFormatException("getChar can't use " + string + " item.");
+ }
+ }
+ else
+ {
+ return (char) c;
+ }
+ }
+
+ public byte[] getBytes(String string) throws JMSException
+ {
+ return getBytes(new AMQShortString(string));
+ }
+
+ public byte[] getBytes(AMQShortString string) throws JMSException
+ {
+ byte[] bs = getHeaders().getBytes(string);
+
+ if (bs == null)
+ {
+ throw new MessageFormatException("getBytes can't use " + string + " item.");
+ }
+ else
+ {
+ return bs;
+ }
+ }
+
+ public byte getByte(String string) throws JMSException
+ {
+ Byte b = getHeaders().getByte(string);
+ if (b == null)
+ {
+ if (getHeaders().containsKey(string))
+ {
+ Object str = getHeaders().getObject(string);
+
+ if (str == null || !(str instanceof String))
+ {
+ throw new MessageFormatException("getByte can't use " + string + " item.");
+ }
+ else
+ {
+ return Byte.valueOf((String) str);
+ }
+ }
+ else
+ {
+ b = Byte.valueOf(null);
+ }
+ }
+
+ return b;
+ }
+
+ public short getShort(String string) throws JMSException
+ {
+ Short s = getHeaders().getShort(string);
+
+ if (s == null)
+ {
+ s = Short.valueOf(getByte(string));
+ }
+
+ return s;
+ }
+
+ public int getInteger(String string) throws JMSException
+ {
+ Integer i = getHeaders().getInteger(string);
+
+ if (i == null)
+ {
+ i = Integer.valueOf(getShort(string));
+ }
+
+ return i;
+ }
+
+ public long getLong(String string) throws JMSException
+ {
+ Long l = getHeaders().getLong(string);
+
+ if (l == null)
+ {
+ l = Long.valueOf(getInteger(string));
+ }
+
+ return l;
+ }
+
+ public float getFloat(String string) throws JMSException
+ {
+ Float f = getHeaders().getFloat(string);
+
+ if (f == null)
+ {
+ if (getHeaders().containsKey(string))
+ {
+ Object str = getHeaders().getObject(string);
+
+ if (str == null || !(str instanceof String))
+ {
+ throw new MessageFormatException("getFloat can't use " + string + " item.");
+ }
+ else
+ {
+ return Float.valueOf((String) str);
+ }
+ }
+ else
+ {
+ f = Float.valueOf(null);
+ }
+
+ }
+
+ return f;
+ }
+
+ public double getDouble(String string) throws JMSException
+ {
+ Double d = getHeaders().getDouble(string);
+
+ if (d == null)
+ {
+ d = Double.valueOf(getFloat(string));
+ }
+
+ return d;
+ }
+
+ public String getString(String string) throws JMSException
+ {
+ String s = getHeaders().getString(string);
+
+ if (s == null)
+ {
+ if (getHeaders().containsKey(string))
+ {
+ Object o = getHeaders().getObject(string);
+ if (o instanceof byte[])
+ {
+ throw new MessageFormatException("getObject couldn't find " + string + " item.");
+ }
+ else
+ {
+ if (o == null)
+ {
+ return null;
+ }
+ else
+ {
+ s = String.valueOf(o);
+ }
+ }
+ }
+ }
+
+ return s;
+ }
+
+ public Object getObject(String string) throws JMSException
+ {
+ return getHeaders().getObject(string);
+ }
+
+ public void setBoolean(AMQShortString string, boolean b) throws JMSException
+ {
+ checkPropertyName(string);
+ getHeaders().setBoolean(string, b);
+ }
+
+ public void setBoolean(String string, boolean b) throws JMSException
+ {
+ checkPropertyName(string);
+ getHeaders().setBoolean(string, b);
+ }
+
+ public void setChar(String string, char c) throws JMSException
+ {
+ checkPropertyName(string);
+ getHeaders().setChar(string, c);
+ }
+
+ public Object setBytes(AMQShortString string, byte[] bytes)
+ {
+ return getHeaders().setBytes(string, bytes);
+ }
+
+ public Object setBytes(String string, byte[] bytes)
+ {
+ return getHeaders().setBytes(string, bytes);
+ }
+
+ public Object setBytes(String string, byte[] bytes, int start, int length)
+ {
+ return getHeaders().setBytes(string, bytes, start, length);
+ }
+
+ public void setByte(String string, byte b) throws JMSException
+ {
+ checkPropertyName(string);
+ getHeaders().setByte(string, b);
+ }
+
+ public void setByte(AMQShortString string, byte b) throws JMSException
+ {
+ checkPropertyName(string);
+ getHeaders().setByte(string, b);
+ }
+
+
+ public void setShort(String string, short i) throws JMSException
+ {
+ checkPropertyName(string);
+ getHeaders().setShort(string, i);
+ }
+
+ public void setInteger(String string, int i) throws JMSException
+ {
+ checkPropertyName(string);
+ getHeaders().setInteger(string, i);
+ }
+
+ public void setInteger(AMQShortString string, int i) throws JMSException
+ {
+ checkPropertyName(string);
+ getHeaders().setInteger(string, i);
+ }
+
+ public void setLong(String string, long l) throws JMSException
+ {
+ checkPropertyName(string);
+ getHeaders().setLong(string, l);
+ }
+
+ public void setFloat(String string, float v) throws JMSException
+ {
+ checkPropertyName(string);
+ getHeaders().setFloat(string, v);
+ }
+
+ public void setDouble(String string, double v) throws JMSException
+ {
+ checkPropertyName(string);
+ getHeaders().setDouble(string, v);
+ }
+
+ public void setString(String string, String string1) throws JMSException
+ {
+ checkPropertyName(string);
+ getHeaders().setString(string, string1);
+ }
+
+ public void setString(AMQShortString string, String string1) throws JMSException
+ {
+ checkPropertyName(string);
+ getHeaders().setString(string, string1);
+ }
+
+ public void setObject(String string, Object object) throws JMSException
+ {
+ checkPropertyName(string);
+ try
+ {
+ getHeaders().setObject(string, object);
+ }
+ catch (AMQPInvalidClassException aice)
+ {
+ throw new MessageFormatException("Only primatives are allowed object is:" + object.getClass());
+ }
+ }
+
+ public boolean itemExists(String string) throws JMSException
+ {
+ return getHeaders().containsKey(string);
+ }
+
+ public Enumeration getPropertyNames()
+ {
+ return getHeaders().getPropertyNames();
+ }
+
+ public void clear()
+ {
+ getHeaders().clear();
+ }
+
+ public boolean propertyExists(AMQShortString propertyName)
+ {
+ return getHeaders().propertyExists(propertyName);
+ }
+
+ public boolean propertyExists(String propertyName)
+ {
+ return getHeaders().propertyExists(propertyName);
+ }
+
+ public Object put(Object key, Object value)
+ {
+ return getHeaders().setObject(key.toString(), value);
+ }
+
+ public Object remove(AMQShortString propertyName)
+ {
+ return getHeaders().remove(propertyName);
+ }
+
+ public Object remove(String propertyName)
+ {
+ return getHeaders().remove(propertyName);
+ }
+
+ public boolean isEmpty()
+ {
+ return getHeaders().isEmpty();
+ }
+
+ public void writeToBuffer(ByteBuffer data)
+ {
+ getHeaders().writeToBuffer(data);
+ }
+
+ public Enumeration getMapNames()
+ {
+ return getPropertyNames();
+ }
+
+ protected static void checkPropertyName(CharSequence propertyName)
+ {
+ if (propertyName == null)
+ {
+ throw new IllegalArgumentException("Property name must not be null");
+ }
+ else if (propertyName.length() == 0)
+ {
+ throw new IllegalArgumentException("Property name must not be the empty string");
+ }
+
+ checkIdentiferFormat(propertyName);
+ }
+
+ protected static void checkIdentiferFormat(CharSequence propertyName)
+ {
+// JMS requirements 3.5.1 Property Names
+// Identifiers:
+// - An identifier is an unlimited-length character sequence that must begin
+// with a Java identifier start character; all following characters must be Java
+// identifier part characters. An identifier start character is any character for
+// which the method Character.isJavaIdentifierStart returns true. This includes
+// '_' and '$'. An identifier part character is any character for which the
+// method Character.isJavaIdentifierPart returns true.
+// - Identifiers cannot be the names NULL, TRUE, or FALSE.
+// – Identifiers cannot be NOT, AND, OR, BETWEEN, LIKE, IN, IS, or
+// ESCAPE.
+// – Identifiers are either header field references or property references. The
+// type of a property value in a message selector corresponds to the type
+// used to set the property. If a property that does not exist in a message is
+// referenced, its value is NULL. The semantics of evaluating NULL values
+// in a selector are described in Section 3.8.1.2, “Null Values.”
+// – The conversions that apply to the get methods for properties do not
+// apply when a property is used in a message selector expression. For
+// example, suppose you set a property as a string value, as in the
+// following:
+// myMessage.setStringProperty("NumberOfOrders", "2");
+// The following expression in a message selector would evaluate to false,
+// because a string cannot be used in an arithmetic expression:
+// "NumberOfOrders > 1"
+// – Identifiers are case sensitive.
+// – Message header field references are restricted to JMSDeliveryMode,
+// JMSPriority, JMSMessageID, JMSTimestamp, JMSCorrelationID, and
+// JMSType. JMSMessageID, JMSCorrelationID, and JMSType values may be
+// null and if so are treated as a NULL value.
+
+ if (Boolean.getBoolean("strict-jms"))
+ {
+ // JMS start character
+ if (!(Character.isJavaIdentifierStart(propertyName.charAt(0))))
+ {
+ throw new IllegalArgumentException("Identifier '" + propertyName + "' does not start with a valid JMS identifier start character");
+ }
+
+ // JMS part character
+ int length = propertyName.length();
+ for (int c = 1; c < length; c++)
+ {
+ if (!(Character.isJavaIdentifierPart(propertyName.charAt(c))))
+ {
+ throw new IllegalArgumentException("Identifier '" + propertyName + "' contains an invalid JMS identifier character");
+ }
+ }
+
+ // JMS invalid names
+ if ((propertyName.equals("NULL")
+ || propertyName.equals("TRUE")
+ || propertyName.equals("FALSE")
+ || propertyName.equals("NOT")
+ || propertyName.equals("AND")
+ || propertyName.equals("OR")
+ || propertyName.equals("BETWEEN")
+ || propertyName.equals("LIKE")
+ || propertyName.equals("IN")
+ || propertyName.equals("IS")
+ || propertyName.equals("ESCAPE")))
+ {
+ throw new IllegalArgumentException("Identifier '" + propertyName + "' is not allowed in JMS");
+ }
+ }
+
+ }
+}
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/JMSMapMessage.java b/java/client/src/main/java/org/apache/qpid/client/message/JMSMapMessage.java
index 04bb8602bf..10be047388 100644
--- a/java/client/src/main/java/org/apache/qpid/client/message/JMSMapMessage.java
+++ b/java/client/src/main/java/org/apache/qpid/client/message/JMSMapMessage.java
@@ -25,13 +25,14 @@ import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
+import org.apache.qpid.framing.AMQShortString;
+import org.apache.qpid.AMQException;
import javax.jms.JMSException;
import javax.jms.MessageFormatException;
import org.apache.log4j.Logger;
import org.apache.mina.common.ByteBuffer;
-import org.apache.qpid.AMQException;
public class JMSMapMessage extends AbstractBytesTypedMessage implements javax.jms.MapMessage
{
@@ -39,10 +40,11 @@ public class JMSMapMessage extends AbstractBytesTypedMessage implements javax.jm
public static final String MIME_TYPE = "jms/map-message";
+ private static final AMQShortString MIME_TYPE_SHORT_STRING = new AMQShortString(MIME_TYPE);
private Map<String,Object> _map = new HashMap<String, Object>();
- JMSMapMessage() throws JMSException
+ public JMSMapMessage() throws JMSException
{
this(null);
}
@@ -67,15 +69,14 @@ public class JMSMapMessage extends AbstractBytesTypedMessage implements javax.jm
}
}
-
public String toBodyString() throws JMSException
{
return _map.toString();
}
- public String getMimeType()
+ public AMQShortString getMimeTypeAsShortString()
{
- return MIME_TYPE;
+ return MIME_TYPE_SHORT_STRING;
}
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/JMSMapMessageFactory.java b/java/client/src/main/java/org/apache/qpid/client/message/JMSMapMessageFactory.java
index 072c9b0f16..ddbf65e408 100644
--- a/java/client/src/main/java/org/apache/qpid/client/message/JMSMapMessageFactory.java
+++ b/java/client/src/main/java/org/apache/qpid/client/message/JMSMapMessageFactory.java
@@ -23,6 +23,7 @@ package org.apache.qpid.client.message;
import javax.jms.JMSException;
import org.apache.mina.common.ByteBuffer;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.AMQException;
public class JMSMapMessageFactory extends AbstractJMSMessageFactory
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/JMSObjectMessage.java b/java/client/src/main/java/org/apache/qpid/client/message/JMSObjectMessage.java
index f8a61b32d3..a2985161ae 100644
--- a/java/client/src/main/java/org/apache/qpid/client/message/JMSObjectMessage.java
+++ b/java/client/src/main/java/org/apache/qpid/client/message/JMSObjectMessage.java
@@ -27,6 +27,7 @@ import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
+import org.apache.qpid.framing.AMQShortString;
import javax.jms.JMSException;
import javax.jms.MessageFormatException;
@@ -37,14 +38,15 @@ import org.apache.qpid.AMQException;
public class JMSObjectMessage extends AbstractJMSMessage implements ObjectMessage
{
- static final String MIME_TYPE = "application/java-object-stream";
+ public static final String MIME_TYPE = "application/java-object-stream";
+ private static final AMQShortString MIME_TYPE_SHORT_STRING = new AMQShortString(MIME_TYPE);
private static final int DEFAULT_BUFFER_SIZE = 1024;
/**
* Creates empty, writable message for use by producers
*/
- JMSObjectMessage()
+ public JMSObjectMessage()
{
this(null);
}
@@ -57,7 +59,7 @@ public class JMSObjectMessage extends AbstractJMSMessage implements ObjectMessag
_data = ByteBuffer.allocate(DEFAULT_BUFFER_SIZE);
_data.setAutoExpand(true);
}
- getMessageHeaders().setContentType(MIME_TYPE);
+ getMessageHeaders().setContentType(MIME_TYPE_SHORT_STRING);
}
/**
@@ -83,9 +85,9 @@ public class JMSObjectMessage extends AbstractJMSMessage implements ObjectMessag
return toString(_data);
}
- public String getMimeType()
+ public AMQShortString getMimeTypeAsShortString()
{
- return MIME_TYPE;
+ return MIME_TYPE_SHORT_STRING;
}
public void setObject(Serializable serializable) throws JMSException
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/JMSObjectMessageFactory.java b/java/client/src/main/java/org/apache/qpid/client/message/JMSObjectMessageFactory.java
index 6980022746..9613ded522 100644
--- a/java/client/src/main/java/org/apache/qpid/client/message/JMSObjectMessageFactory.java
+++ b/java/client/src/main/java/org/apache/qpid/client/message/JMSObjectMessageFactory.java
@@ -24,6 +24,7 @@ import javax.jms.JMSException;
import org.apache.mina.common.ByteBuffer;
import org.apache.qpid.AMQException;
+import org.apache.qpid.framing.AMQShortString;
public class JMSObjectMessageFactory extends AbstractJMSMessageFactory
{
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/JMSStreamMessage.java b/java/client/src/main/java/org/apache/qpid/client/message/JMSStreamMessage.java
index 6be367f07a..7bf5c760b5 100644
--- a/java/client/src/main/java/org/apache/qpid/client/message/JMSStreamMessage.java
+++ b/java/client/src/main/java/org/apache/qpid/client/message/JMSStreamMessage.java
@@ -25,6 +25,7 @@ import javax.jms.StreamMessage;
import org.apache.mina.common.ByteBuffer;
import org.apache.qpid.AMQException;
+import org.apache.qpid.framing.AMQShortString;
/**
* @author Apache Software Foundation
@@ -32,6 +33,7 @@ import org.apache.qpid.AMQException;
public class JMSStreamMessage extends AbstractBytesTypedMessage implements StreamMessage
{
public static final String MIME_TYPE="jms/stream-message";
+ private static final AMQShortString MIME_TYPE_SHORT_STRING = new AMQShortString(MIME_TYPE);
/**
@@ -40,7 +42,7 @@ public class JMSStreamMessage extends AbstractBytesTypedMessage implements Strea
*/
private int _byteArrayRemaining = -1;
- JMSStreamMessage()
+ public JMSStreamMessage()
{
this(null);
}
@@ -69,9 +71,9 @@ public class JMSStreamMessage extends AbstractBytesTypedMessage implements Strea
_readableMessage = true;
}
- public String getMimeType()
+ public AMQShortString getMimeTypeAsShortString()
{
- return MIME_TYPE;
+ return MIME_TYPE_SHORT_STRING;
}
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/JMSStreamMessageFactory.java b/java/client/src/main/java/org/apache/qpid/client/message/JMSStreamMessageFactory.java
index 7517fea16d..86b9a2a899 100644
--- a/java/client/src/main/java/org/apache/qpid/client/message/JMSStreamMessageFactory.java
+++ b/java/client/src/main/java/org/apache/qpid/client/message/JMSStreamMessageFactory.java
@@ -23,6 +23,7 @@ package org.apache.qpid.client.message;
import javax.jms.JMSException;
import org.apache.mina.common.ByteBuffer;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.AMQException;
public class JMSStreamMessageFactory extends AbstractJMSMessageFactory
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/JMSTextMessage.java b/java/client/src/main/java/org/apache/qpid/client/message/JMSTextMessage.java
index a436f2b0f1..51712ef88d 100644
--- a/java/client/src/main/java/org/apache/qpid/client/message/JMSTextMessage.java
+++ b/java/client/src/main/java/org/apache/qpid/client/message/JMSTextMessage.java
@@ -20,6 +20,9 @@
*/
package org.apache.qpid.client.message;
+import org.apache.qpid.framing.AMQShortString;
+import org.apache.qpid.AMQException;
+
import java.io.UnsupportedEncodingException;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
@@ -27,42 +30,49 @@ import java.nio.charset.Charset;
import javax.jms.JMSException;
import org.apache.mina.common.ByteBuffer;
-import org.apache.qpid.AMQException;
public class JMSTextMessage extends AbstractJMSMessage implements javax.jms.TextMessage
{
private static final String MIME_TYPE = "text/plain";
+ private static final AMQShortString MIME_TYPE_SHORT_STRING = new AMQShortString(MIME_TYPE);
+
private String _decodedValue;
/**
* This constant represents the name of a property that is set when the message payload is null.
*/
- private static final String PAYLOAD_NULL_PROPERTY = "JMS_QPID_NULL";
+ private static final AMQShortString PAYLOAD_NULL_PROPERTY = new AMQShortString("JMS_QPID_NULL");
+ private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
- JMSTextMessage() throws JMSException
+ public JMSTextMessage() throws JMSException
{
- this(null, null);
+ this(null, (AMQShortString)null);
}
- JMSTextMessage(ByteBuffer data, String encoding) throws JMSException
+ JMSTextMessage(ByteBuffer data, AMQShortString encoding) throws JMSException
{
super(data); // this instantiates a content header
- getMessageHeaders().setContentType(MIME_TYPE);
+ getMessageHeaders().setContentType(MIME_TYPE_SHORT_STRING);
getMessageHeaders().setEncoding(encoding);
}
+ JMSTextMessage(ByteBuffer data, String encoding) throws JMSException
+ {
+ this(data, new AMQShortString(encoding));
+ }
+
JMSTextMessage(long deliveryTag, MessageHeaders contentHeader, ByteBuffer data)
throws AMQException
{
super(deliveryTag, contentHeader, data);
- contentHeader.setContentType(MIME_TYPE);
+ contentHeader.setContentType(MIME_TYPE_SHORT_STRING);
_data = data;
}
JMSTextMessage(ByteBuffer data) throws JMSException
{
- this(data, null);
+ this(data, (AMQShortString)null);
}
JMSTextMessage(String text) throws JMSException
@@ -91,9 +101,9 @@ public class JMSTextMessage extends AbstractJMSMessage implements javax.jms.Text
_data = data;
}
- public String getMimeType()
+ public AMQShortString getMimeTypeAsShortString()
{
- return MIME_TYPE;
+ return MIME_TYPE_SHORT_STRING;
}
public void setText(String text) throws JMSException
@@ -115,7 +125,7 @@ public class JMSTextMessage extends AbstractJMSMessage implements javax.jms.Text
}
else
{
- _data.put(text.getBytes(getMessageHeaders().getEncoding()));
+ _data.put(text.getBytes(getMessageHeaders().getEncoding().asString()));
}
_changedData=true;
}
@@ -151,7 +161,7 @@ public class JMSTextMessage extends AbstractJMSMessage implements javax.jms.Text
{
try
{
- _decodedValue = _data.getString(Charset.forName(getMessageHeaders().getEncoding()).newDecoder());
+ _decodedValue = _data.getString(Charset.forName(getMessageHeaders().getEncoding().asString()).newDecoder());
}
catch (CharacterCodingException e)
{
@@ -164,7 +174,7 @@ public class JMSTextMessage extends AbstractJMSMessage implements javax.jms.Text
{
try
{
- _decodedValue = _data.getString(Charset.defaultCharset().newDecoder());
+ _decodedValue = _data.getString(DEFAULT_CHARSET.newDecoder());
}
catch (CharacterCodingException e)
{
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/JMSTextMessageFactory.java b/java/client/src/main/java/org/apache/qpid/client/message/JMSTextMessageFactory.java
index 64b1fc3892..27882b65fc 100644
--- a/java/client/src/main/java/org/apache/qpid/client/message/JMSTextMessageFactory.java
+++ b/java/client/src/main/java/org/apache/qpid/client/message/JMSTextMessageFactory.java
@@ -24,6 +24,7 @@ import javax.jms.JMSException;
import org.apache.mina.common.ByteBuffer;
import org.apache.qpid.AMQException;
+import org.apache.qpid.framing.AMQShortString;
public class JMSTextMessageFactory extends AbstractJMSMessageFactory
{
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/MessageConverter.java b/java/client/src/main/java/org/apache/qpid/client/message/MessageConverter.java
new file mode 100644
index 0000000000..58089f595b
--- /dev/null
+++ b/java/client/src/main/java/org/apache/qpid/client/message/MessageConverter.java
@@ -0,0 +1,179 @@
+/*
+ *
+ * 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.client.message;
+
+import org.apache.log4j.Logger;
+
+import javax.jms.*;
+import java.util.Enumeration;
+
+public class MessageConverter {
+
+ /**
+ * Log4J logger
+ */
+ protected final Logger _logger = Logger.getLogger(getClass());
+
+ /**
+ * AbstractJMSMessage which will hold the converted message
+ */
+ private AbstractJMSMessage _newMessage;
+
+ public MessageConverter(AbstractJMSMessage message) throws JMSException
+ {
+ _newMessage = message;
+ }
+
+ public MessageConverter(BytesMessage message) throws JMSException
+ {
+ BytesMessage bytesMessage = (BytesMessage) message;
+ bytesMessage.reset();
+
+ JMSBytesMessage nativeMsg = new JMSBytesMessage();
+
+ byte[] buf = new byte[1024];
+
+ int len;
+
+ while ((len = bytesMessage.readBytes(buf)) != -1)
+ {
+ nativeMsg.writeBytes(buf, 0, len);
+ }
+
+ _newMessage = nativeMsg;
+ setMessageProperties(message);
+ }
+
+ public MessageConverter(MapMessage message) throws JMSException
+ {
+ MapMessage nativeMessage = new JMSMapMessage();
+
+ Enumeration mapNames = message.getMapNames();
+ while (mapNames.hasMoreElements())
+ {
+ String name = (String) mapNames.nextElement();
+ nativeMessage.setObject(name, message.getObject(name));
+ }
+ _newMessage = (AbstractJMSMessage) nativeMessage;
+ setMessageProperties(message);
+ }
+
+ public MessageConverter(ObjectMessage message) throws JMSException
+ {
+ ObjectMessage origMessage = (ObjectMessage) message;
+ ObjectMessage nativeMessage = new JMSObjectMessage();
+
+ nativeMessage.setObject(origMessage.getObject());
+
+ _newMessage = (AbstractJMSMessage) nativeMessage;
+ setMessageProperties(message);
+
+ }
+
+ public MessageConverter(TextMessage message) throws JMSException
+ {
+ TextMessage nativeMessage = new JMSTextMessage();
+
+ nativeMessage.setText(message.getText());
+
+ _newMessage = (AbstractJMSMessage) nativeMessage;
+ setMessageProperties(message);
+ }
+
+ public MessageConverter(StreamMessage message) throws JMSException
+ {
+ StreamMessage nativeMessage = new JMSStreamMessage();
+
+ try
+ {
+ message.reset();
+ while (true)
+ {
+ nativeMessage.writeObject(message.readObject());
+ }
+ }
+ catch (MessageEOFException e)
+ {
+ //we're at the end so don't mind the exception
+ }
+ _newMessage = (AbstractJMSMessage) nativeMessage;
+ setMessageProperties(message);
+ }
+
+ public AbstractJMSMessage getConvertedMessage()
+ {
+ return _newMessage;
+ }
+
+ /**
+ * Sets all message properties
+ */
+ protected void setMessageProperties(Message message) throws JMSException
+ {
+ setNonJMSProperties(message);
+ setJMSProperties(message);
+ }
+
+ /**
+ * Sets all non-JMS defined properties on converted message
+ */
+ protected void setNonJMSProperties(Message message) throws JMSException
+ {
+ Enumeration propertyNames = message.getPropertyNames();
+ while (propertyNames.hasMoreElements())
+ {
+ String propertyName = String.valueOf(propertyNames.nextElement());
+ //TODO: Shouldn't need to check for JMS properties here as don't think getPropertyNames() should return them
+ if (!propertyName.startsWith("JMSX_"))
+ {
+ Object value = message.getObjectProperty(propertyName);
+ _newMessage.setObjectProperty(propertyName, value);
+ }
+ }
+ }
+
+ /**
+ * Exposed JMS defined properties on converted message:
+ * JMSDestination - we don't set here
+ * JMSDeliveryMode - set
+ * JMSExpiration - we don't set here
+ * JMSPriority - we don't set here
+ * JMSMessageID - we don't set here
+ * JMSTimestamp - we don't set here
+ * JMSCorrelationID - set
+ * JMSReplyTo - set
+ * JMSType - set
+ * JMSRedlivered - we don't set here
+ */
+ protected void setJMSProperties(Message message) throws JMSException
+ {
+ _newMessage.setJMSDeliveryMode(message.getJMSDeliveryMode());
+
+ if (message.getJMSReplyTo() != null)
+ {
+ _newMessage.setJMSReplyTo(message.getJMSReplyTo());
+ }
+ _newMessage.setJMSType(message.getJMSType());
+
+ _newMessage.setJMSCorrelationID(message.getJMSCorrelationID());
+ }
+
+}
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/MessageFactory.java b/java/client/src/main/java/org/apache/qpid/client/message/MessageFactory.java
index 17c735fd0e..027c7d7728 100644
--- a/java/client/src/main/java/org/apache/qpid/client/message/MessageFactory.java
+++ b/java/client/src/main/java/org/apache/qpid/client/message/MessageFactory.java
@@ -23,6 +23,7 @@ package org.apache.qpid.client.message;
import java.util.List;
import org.apache.qpid.AMQException;
+import org.apache.qpid.framing.AMQShortString;
import javax.jms.JMSException;
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/MessageFactoryRegistry.java b/java/client/src/main/java/org/apache/qpid/client/message/MessageFactoryRegistry.java
index c7a7cd892b..d16b7f6b02 100644
--- a/java/client/src/main/java/org/apache/qpid/client/message/MessageFactoryRegistry.java
+++ b/java/client/src/main/java/org/apache/qpid/client/message/MessageFactoryRegistry.java
@@ -28,10 +28,12 @@ import javax.jms.JMSException;
import org.apache.qpid.AMQException;
import org.apache.qpid.framing.Content;
+import org.apache.qpid.framing.AMQShortString;
public class MessageFactoryRegistry
{
- private final Map _mimeToFactoryMap = new HashMap();
+ private final Map<String, MessageFactory> _mimeStringToFactoryMap = new HashMap<String, MessageFactory>();
+ private final Map<AMQShortString, MessageFactory> _mimeShortStringToFactoryMap = new HashMap<AMQShortString, MessageFactory>();
public void registerFactory(String mimeType, MessageFactory mf)
{
@@ -39,12 +41,14 @@ public class MessageFactoryRegistry
{
throw new IllegalArgumentException("Message factory must not be null");
}
- _mimeToFactoryMap.put(mimeType, mf);
+ _mimeStringToFactoryMap.put(mimeType, mf);
+ _mimeShortStringToFactoryMap.put(new AMQShortString(mimeType), mf);
}
public MessageFactory deregisterFactory(String mimeType)
{
- return (MessageFactory) _mimeToFactoryMap.remove(mimeType);
+ _mimeShortStringToFactoryMap.remove(new AMQShortString(mimeType));
+ return _mimeStringToFactoryMap.remove(mimeType);
}
/**
@@ -62,7 +66,7 @@ public class MessageFactoryRegistry
MessageHeaders contentHeader,
List contents) throws AMQException, JMSException
{
- MessageFactory mf = (MessageFactory) _mimeToFactoryMap.get(contentHeader.getContentType());
+ MessageFactory mf = _mimeShortStringToFactoryMap.get(contentHeader.getContentType());
if (mf == null)
{
throw new AMQException("Unsupport MIME type of " + contentHeader.getContentType());
@@ -79,7 +83,7 @@ public class MessageFactoryRegistry
{
throw new IllegalArgumentException("Mime type must not be null");
}
- MessageFactory mf = (MessageFactory) _mimeToFactoryMap.get(mimeType);
+ MessageFactory mf = _mimeStringToFactoryMap.get(mimeType);
if (mf == null)
{
throw new AMQException("Unsupport MIME type of " + mimeType);
@@ -100,7 +104,7 @@ public class MessageFactoryRegistry
mf.registerFactory(JMSMapMessage.MIME_TYPE, new JMSMapMessageFactory());
mf.registerFactory("text/plain", new JMSTextMessageFactory());
mf.registerFactory("text/xml", new JMSTextMessageFactory());
- mf.registerFactory("application/octet-stream", new JMSBytesMessageFactory());
+ mf.registerFactory(JMSBytesMessage.MIME_TYPE, new JMSBytesMessageFactory());
mf.registerFactory(JMSObjectMessage.MIME_TYPE, new JMSObjectMessageFactory());
mf.registerFactory(JMSStreamMessage.MIME_TYPE, new JMSStreamMessageFactory());
mf.registerFactory(null, new JMSBytesMessageFactory());
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/MessageHeaders.java b/java/client/src/main/java/org/apache/qpid/client/message/MessageHeaders.java
index 72e920ffd3..1ab03ee34e 100644
--- a/java/client/src/main/java/org/apache/qpid/client/message/MessageHeaders.java
+++ b/java/client/src/main/java/org/apache/qpid/client/message/MessageHeaders.java
@@ -24,6 +24,7 @@ package org.apache.qpid.client.message;
import org.apache.log4j.Logger;
import org.apache.mina.common.ByteBuffer;
import org.apache.qpid.AMQPInvalidClassException;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.framing.FieldTable;
import org.apache.qpid.framing.FieldTableFactory;
@@ -35,13 +36,13 @@ public class MessageHeaders
{
private static final Logger _logger = Logger.getLogger(MessageHeaders.class);
- private String _contentType;
+ private AMQShortString _contentType;
- private String _encoding;
+ private AMQShortString _encoding;
- private String _destination;
+ private AMQShortString _destination;
- private String _exchange;
+ private AMQShortString _exchange;
private FieldTable _jmsHeaders;
@@ -49,33 +50,35 @@ public class MessageHeaders
private short _priority;
- private String _correlationId;
+ private AMQShortString _correlationId;
- private String _replyTo;
+ private AMQShortString _replyTo;
private long _expiration;
- private String _messageId;
+ private AMQShortString _messageId;
private long _timestamp;
- private String _type;
+ private AMQShortString _type;
- private String _userId;
+ private AMQShortString _userId;
- private String _appId;
+ private AMQShortString _appId;
- private String _transactionId;
+ private AMQShortString _transactionId;
- private String _routingKey;
+ private AMQShortString _routingKey;
private int _size;
- public int getSize() {
+ public int getSize()
+ {
return _size;
}
- public void setSize(int size) {
+ public void setSize(int size)
+ {
this._size = size;
}
@@ -83,29 +86,24 @@ public class MessageHeaders
{
}
- public String getContentTypeShortString()
+ public AMQShortString getContentType()
{
return _contentType;
}
- public String getContentType()
+ public void setContentType(AMQShortString contentType)
{
- return _contentType == null ? null : _contentType.toString();
+ _contentType = contentType;
}
- public void setContentType(String contentType)
+ public AMQShortString getEncoding()
{
- _contentType = contentType == null ? null : new String(contentType);
+ return _encoding;
}
- public String getEncoding()
+ public void setEncoding(AMQShortString encoding)
{
- return _encoding == null ? null : _encoding.toString();
- }
-
- public void setEncoding(String encoding)
- {
- _encoding = encoding == null ? null : new String(encoding);
+ _encoding = encoding;
}
public FieldTable getJMSHeaders()
@@ -144,22 +142,22 @@ public class MessageHeaders
_priority = priority;
}
- public String getCorrelationId()
+ public AMQShortString getCorrelationId()
{
- return _correlationId == null ? null : _correlationId.toString();
+ return _correlationId;
}
- public void setCorrelationId(String correlationId)
+ public void setCorrelationId(AMQShortString correlationId)
{
- _correlationId = correlationId == null ? null : new String(correlationId);
+ _correlationId = correlationId;
}
- public String getReplyTo()
+ public AMQShortString getReplyTo()
{
- return _replyTo == null ? null : _replyTo.toString();
+ return _replyTo;
}
- public void setReplyTo(String replyTo)
+ public void setReplyTo(AMQShortString replyTo)
{
_replyTo = replyTo;
}
@@ -175,12 +173,12 @@ public class MessageHeaders
}
- public String getMessageId()
+ public AMQShortString getMessageId()
{
return _messageId;
}
- public void setMessageId(String messageId)
+ public void setMessageId(AMQShortString messageId)
{
_messageId = messageId;
}
@@ -195,39 +193,39 @@ public class MessageHeaders
_timestamp = timestamp;
}
- public String getType()
+ public AMQShortString getType()
{
- return _type == null ? null : _type.toString();
+ return _type;
}
- public void setType(String type)
+ public void setType(AMQShortString type)
{
- _type = type == null ? null : new String(type);
+ _type = type;
}
- public String getUserId()
+ public AMQShortString getUserId()
{
- return _userId == null ? null : _userId.toString();
+ return _userId;
}
- public void setUserId(String userId)
+ public void setUserId(AMQShortString userId)
{
- _userId = userId == null ? null : new String(userId);
+ _userId = userId;
}
- public String getAppId()
+ public AMQShortString getAppId()
{
- return _appId == null ? null : _appId.toString();
+ return _appId;
}
- public void setAppId(String appId)
+ public void setAppId(AMQShortString appId)
{
- _appId = appId == null ? null : new String(appId);
+ _appId = appId;
}
// MapMessage Interface
- public boolean getBoolean(String string) throws JMSException
+ public boolean getBoolean(AMQShortString string) throws JMSException
{
Boolean b = getJMSHeaders().getBoolean(string);
@@ -237,13 +235,13 @@ public class MessageHeaders
{
Object str = getJMSHeaders().getObject(string);
- if (str == null || !(str instanceof String))
+ if (str == null || !(str instanceof AMQShortString))
{
throw new MessageFormatException("getBoolean can't use " + string + " item.");
}
else
{
- return Boolean.valueOf((String) str);
+ return Boolean.valueOf(((AMQShortString)str).asString());
}
}
else
@@ -255,13 +253,13 @@ public class MessageHeaders
return b;
}
- public char getCharacter(String string) throws JMSException
+ public char getCharacter(AMQShortString string) throws JMSException
{
Character c = getJMSHeaders().getCharacter(string);
if (c == null)
{
- if (getJMSHeaders().isNullStringValue(string))
+ if (getJMSHeaders().isNullStringValue(string.asString()))
{
throw new NullPointerException("Cannot convert null char");
}
@@ -276,7 +274,7 @@ public class MessageHeaders
}
}
- public byte[] getBytes(String string) throws JMSException
+ public byte[] getBytes(AMQShortString string) throws JMSException
{
byte[] bs = getJMSHeaders().getBytes(string);
@@ -290,7 +288,7 @@ public class MessageHeaders
}
}
- public byte getByte(String string) throws JMSException
+ public byte getByte(AMQShortString string) throws JMSException
{
Byte b = getJMSHeaders().getByte(string);
if (b == null)
@@ -299,13 +297,13 @@ public class MessageHeaders
{
Object str = getJMSHeaders().getObject(string);
- if (str == null || !(str instanceof String))
+ if (str == null || !(str instanceof AMQShortString))
{
throw new MessageFormatException("getByte can't use " + string + " item.");
}
else
{
- return Byte.valueOf((String) str);
+ return Byte.valueOf(((AMQShortString)str).asString());
}
}
else
@@ -317,7 +315,7 @@ public class MessageHeaders
return b;
}
- public short getShort(String string) throws JMSException
+ public short getShort(AMQShortString string) throws JMSException
{
Short s = getJMSHeaders().getShort(string);
@@ -329,7 +327,7 @@ public class MessageHeaders
return s;
}
- public int getInteger(String string) throws JMSException
+ public int getInteger(AMQShortString string) throws JMSException
{
Integer i = getJMSHeaders().getInteger(string);
@@ -341,7 +339,7 @@ public class MessageHeaders
return i;
}
- public long getLong(String string) throws JMSException
+ public long getLong(AMQShortString string) throws JMSException
{
Long l = getJMSHeaders().getLong(string);
@@ -353,7 +351,7 @@ public class MessageHeaders
return l;
}
- public float getFloat(String string) throws JMSException
+ public float getFloat(AMQShortString string) throws JMSException
{
Float f = getJMSHeaders().getFloat(string);
@@ -363,13 +361,13 @@ public class MessageHeaders
{
Object str = getJMSHeaders().getObject(string);
- if (str == null || !(str instanceof String))
+ if (str == null || !(str instanceof AMQShortString))
{
throw new MessageFormatException("getFloat can't use " + string + " item.");
}
else
{
- return Float.valueOf((String) str);
+ return Float.valueOf(((AMQShortString)str).asString());
}
}
else
@@ -382,7 +380,7 @@ public class MessageHeaders
return f;
}
- public double getDouble(String string) throws JMSException
+ public double getDouble(AMQShortString string) throws JMSException
{
Double d = getJMSHeaders().getDouble(string);
@@ -394,9 +392,9 @@ public class MessageHeaders
return d;
}
- public String getString(String string) throws JMSException
+ public AMQShortString getString(AMQShortString string) throws JMSException
{
- String s = getJMSHeaders().getString(string);
+ AMQShortString s = new AMQShortString(getJMSHeaders().getString(string.asString()));
if (s == null)
{
@@ -415,7 +413,7 @@ public class MessageHeaders
}
else
{
- s = String.valueOf(o);
+ s = (AMQShortString) o;
}
}
}
@@ -424,76 +422,76 @@ public class MessageHeaders
return s;
}
- public Object getObject(String string) throws JMSException
+ public Object getObject(AMQShortString string) throws JMSException
{
return getJMSHeaders().getObject(string);
}
- public void setBoolean(String string, boolean b) throws JMSException
+ public void setBoolean(AMQShortString string, boolean b) throws JMSException
{
checkPropertyName(string);
getJMSHeaders().setBoolean(string, b);
}
- public void setChar(String string, char c) throws JMSException
+ public void setChar(AMQShortString string, char c) throws JMSException
{
checkPropertyName(string);
getJMSHeaders().setChar(string, c);
}
- public Object setBytes(String string, byte[] bytes)
+ public Object setBytes(AMQShortString string, byte[] bytes)
{
return getJMSHeaders().setBytes(string, bytes);
}
- public Object setBytes(String string, byte[] bytes, int start, int length)
+ public Object setBytes(AMQShortString string, byte[] bytes, int start, int length)
{
return getJMSHeaders().setBytes(string, bytes, start, length);
}
- public void setByte(String string, byte b) throws JMSException
+ public void setByte(AMQShortString string, byte b) throws JMSException
{
checkPropertyName(string);
getJMSHeaders().setByte(string, b);
}
- public void setShort(String string, short i) throws JMSException
+ public void setShort(AMQShortString string, short i) throws JMSException
{
checkPropertyName(string);
getJMSHeaders().setShort(string, i);
}
- public void setInteger(String string, int i) throws JMSException
+ public void setInteger(AMQShortString string, int i) throws JMSException
{
checkPropertyName(string);
getJMSHeaders().setInteger(string, i);
}
- public void setLong(String string, long l) throws JMSException
+ public void setLong(AMQShortString string, long l) throws JMSException
{
checkPropertyName(string);
getJMSHeaders().setLong(string, l);
}
- public void setFloat(String string, float v) throws JMSException
+ public void setFloat(AMQShortString string, float v) throws JMSException
{
checkPropertyName(string);
getJMSHeaders().setFloat(string, v);
}
- public void setDouble(String string, double v) throws JMSException
+ public void setDouble(AMQShortString string, double v) throws JMSException
{
checkPropertyName(string);
getJMSHeaders().setDouble(string, v);
}
- public void setString(String string, String string1) throws JMSException
+ public void setString(AMQShortString string, AMQShortString string1) throws JMSException
{
checkPropertyName(string);
- getJMSHeaders().setString(string, string1);
+ getJMSHeaders().setString(string.asString(), string1.asString());
}
- public void setObject(String string, Object object) throws JMSException
+ public void setObject(AMQShortString string, Object object) throws JMSException
{
checkPropertyName(string);
try
@@ -506,7 +504,7 @@ public class MessageHeaders
}
}
- public boolean itemExists(String string) throws JMSException
+ public boolean itemExists(AMQShortString string) throws JMSException
{
return getJMSHeaders().containsKey(string);
}
@@ -521,7 +519,7 @@ public class MessageHeaders
getJMSHeaders().clear();
}
- public boolean propertyExists(String propertyName)
+ public boolean propertyExists(AMQShortString propertyName)
{
return getJMSHeaders().propertyExists(propertyName);
}
@@ -531,7 +529,7 @@ public class MessageHeaders
return getJMSHeaders().setObject(key.toString(), value);
}
- public Object remove(String propertyName)
+ public Object remove(AMQShortString propertyName)
{
return getJMSHeaders().remove(propertyName);
}
@@ -637,35 +635,43 @@ public class MessageHeaders
}
- public String getTransactionId() {
+ public AMQShortString getTransactionId()
+ {
return _transactionId;
}
- public void setTransactionId(String id) {
+ public void setTransactionId(AMQShortString id)
+ {
_transactionId = id;
}
- public String getDestination() {
+ public AMQShortString getDestination()
+ {
return _destination;
}
- public void setDestination(String destination) {
+ public void setDestination(AMQShortString destination)
+ {
this._destination = destination;
}
- public String getExchange() {
+ public AMQShortString getExchange()
+ {
return _exchange;
}
- public void setExchange(String exchange) {
+ public void setExchange(AMQShortString exchange)
+ {
this._exchange = exchange;
}
- public String getRoutingKey() {
+ public AMQShortString getRoutingKey()
+ {
return _routingKey;
}
- public void setRoutingKey(String routingKey) {
+ public void setRoutingKey(AMQShortString routingKey)
+ {
this._routingKey = routingKey;
}
}
diff --git a/java/client/src/main/java/org/apache/qpid/client/message/UnprocessedMessage.java b/java/client/src/main/java/org/apache/qpid/client/message/UnprocessedMessage.java
index ea1c3c02c8..dd3140e8d8 100644
--- a/java/client/src/main/java/org/apache/qpid/client/message/UnprocessedMessage.java
+++ b/java/client/src/main/java/org/apache/qpid/client/message/UnprocessedMessage.java
@@ -24,28 +24,69 @@ import java.util.LinkedList;
import java.util.List;
/**
- * This class contains everything needed to process a JMS message. It assembles the
- * deliver body, the content header and the content body/ies.
+ * This class contains everything needed to process a JMS message.
*
* Note that the actual work of creating a JMS message for the client code's use is done
* outside of the MINA dispatcher thread in order to minimise the amount of work done in
* the MINA dispatcher thread.
*
*/
-public class UnprocessedMessage {
- public int bytesReceived = 0;
+public class UnprocessedMessage
+{
+ private int bytesReceived = 0;
+ private int channelId;
+ private List<byte[]> contents = new LinkedList();
+ private long deliveryTag;
+ private MessageHeaders messageHeaders;
+
+ public UnprocessedMessage(int channelId, long deliveryTag, MessageHeaders messageHeaders)
+ {
+ this.channelId = channelId;
+ this.deliveryTag = deliveryTag;
+ this.messageHeaders = messageHeaders;
+ }
+
+ public UnprocessedMessage(int channelId, long deliveryTag, MessageHeaders messageHeaders, byte[] content)
+ {
+ this.channelId = channelId;
+ this.deliveryTag = deliveryTag;
+ this.messageHeaders = messageHeaders;
+ addContent(content);
+ }
- public List contents = new LinkedList();
-
- public int channelId;
-
- public long deliveryTag;
-
- public MessageHeaders contentHeader;
-
- public void addContent(byte[] content) {
+ public void addContent(byte[] content)
+ {
contents.add(content);
- bytesReceived = bytesReceived + content.length;
+ bytesReceived += content.length;
}
+ public int getBytesReceived()
+ {
+ return bytesReceived;
+ }
+
+ public int getChannelId()
+ {
+ return channelId;
+ }
+
+ public List<byte[]> getContents()
+ {
+ return contents;
+ }
+
+ public long getDeliveryTag()
+ {
+ return deliveryTag;
+ }
+
+ public MessageHeaders getMessageHeaders()
+ {
+ return messageHeaders;
+ }
+
+ public String toString()
+ {
+ return "UnprocessedMessage: ch=" + channelId + "; bytesReceived=" + bytesReceived + "; deliveryTag=" + deliveryTag + "; MsgHdrs=" + messageHeaders + "Num contents=" + contents.size() + "; First content=" + new String(contents.get(0));
+ }
}
diff --git a/java/client/src/main/java/org/apache/qpid/client/protocol/AMQProtocolHandler.java b/java/client/src/main/java/org/apache/qpid/client/protocol/AMQProtocolHandler.java
index 4d15c3cb35..c38f925b1e 100644
--- a/java/client/src/main/java/org/apache/qpid/client/protocol/AMQProtocolHandler.java
+++ b/java/client/src/main/java/org/apache/qpid/client/protocol/AMQProtocolHandler.java
@@ -24,11 +24,15 @@ import org.apache.log4j.Logger;
import org.apache.mina.common.IdleStatus;
import org.apache.mina.common.IoHandlerAdapter;
import org.apache.mina.common.IoSession;
+import org.apache.mina.common.IoServiceConfig;
import org.apache.mina.filter.SSLFilter;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.qpid.AMQConnectionClosedException;
import org.apache.qpid.AMQDisconnectedException;
import org.apache.qpid.AMQException;
+import org.apache.qpid.AMQTimeoutException;
+import org.apache.qpid.pool.ReadWriteThreadModel;
+import org.apache.qpid.protocol.AMQMethodEvent;
import org.apache.qpid.client.AMQConnection;
import org.apache.qpid.client.AMQSession;
import org.apache.qpid.client.failover.FailoverHandler;
@@ -37,11 +41,13 @@ import org.apache.qpid.client.state.AMQState;
import org.apache.qpid.client.state.AMQStateManager;
import org.apache.qpid.client.state.listener.SpecificMethodFrameListener;
import org.apache.qpid.codec.AMQCodecFactory;
+import org.apache.qpid.framing.AMQBody;
import org.apache.qpid.framing.AMQDataBlock;
import org.apache.qpid.framing.AMQFrame;
import org.apache.qpid.framing.AMQMethodBody;
import org.apache.qpid.framing.AMQRequestBody;
import org.apache.qpid.framing.AMQResponseBody;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.framing.ConnectionCloseBody;
import org.apache.qpid.framing.ConnectionCloseOkBody;
import org.apache.qpid.framing.HeartbeatBody;
@@ -54,6 +60,7 @@ import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.CountDownLatch;
+
public class AMQProtocolHandler extends IoHandlerAdapter
{
private static final Logger _logger = Logger.getLogger(AMQProtocolHandler.class);
@@ -95,24 +102,11 @@ public class AMQProtocolHandler extends IoHandlerAdapter
private CountDownLatch _failoverLatch;
+ private final long DEFAULT_SYNC_TIMEOUT = 1000 * 30;
+
public AMQProtocolHandler(AMQConnection con)
{
_connection = con;
-
- // We add a proxy for the state manager so that we can substitute the state manager easily in this class.
- // We substitute the state manager when performing failover
- _frameListeners.add(new AMQMethodListener()
- {
- public boolean methodReceived(AMQMethodEvent evt) throws AMQException
- {
- return _stateManager.methodReceived(evt);
- }
-
- public void error(Exception e)
- {
- _stateManager.error(e);
- }
- });
}
public boolean isUseSSL()
@@ -149,13 +143,25 @@ public class AMQProtocolHandler extends IoHandlerAdapter
session.getFilterChain().addBefore("protocolFilter", "ssl", sslFilter);
}
+ try
+ {
+
+ ReadWriteThreadModel threadModel = ReadWriteThreadModel.getInstance();
+ threadModel.getAsynchronousReadFilter().createNewJobForSession(session);
+ threadModel.getAsynchronousWriteFilter().createNewJobForSession(session);
+ }
+ catch (RuntimeException e)
+ {
+ e.printStackTrace();
+ }
+
_protocolSession = new AMQProtocolSession(this, session, _connection, getStateManager());
_protocolSession.init();
}
public void sessionOpened(IoSession session) throws Exception
{
- System.setProperty("foo", "bar");
+ //System.setProperty("foo", "bar");
}
/**
@@ -286,11 +292,14 @@ public class AMQProtocolHandler extends IoHandlerAdapter
public void propagateExceptionToWaiters(Exception e)
{
getStateManager().error(e);
- final Iterator it = _frameListeners.iterator();
- while (it.hasNext())
+ if (!_frameListeners.isEmpty())
{
- final AMQMethodListener ml = (AMQMethodListener) it.next();
- ml.error(e);
+ final Iterator it = _frameListeners.iterator();
+ while (it.hasNext())
+ {
+ final AMQMethodListener ml = (AMQMethodListener) it.next();
+ ml.error(e);
+ }
}
}
@@ -298,59 +307,26 @@ public class AMQProtocolHandler extends IoHandlerAdapter
public void messageReceived(IoSession session, Object message) throws Exception
{
+ final boolean debug = _logger.isDebugEnabled();
+ final long msgNumber = ++_messageReceivedCount;
- if (_messageReceivedCount++ % 1000 == 0)
+ if (debug && (msgNumber % 1000 == 0))
{
_logger.debug("Received " + _messageReceivedCount + " protocol messages");
}
- Iterator it = _frameListeners.iterator();
- AMQFrame frame = (AMQFrame) message;
- HeartbeatDiagnostics.received(frame.bodyFrame instanceof HeartbeatBody);
+ AMQFrame frame = (AMQFrame) message;
+ final AMQBody bodyFrame = frame.getBodyFrame();
- if (frame.bodyFrame instanceof AMQRequestBody)
+ if (bodyFrame instanceof AMQRequestBody)
{
- _protocolSession.messageRequestBodyReceived(frame.channel, (AMQRequestBody)frame.bodyFrame);
+ _protocolSession.messageRequestBodyReceived(frame.getChannel(), (AMQRequestBody)bodyFrame);
}
- else if (frame.bodyFrame instanceof AMQResponseBody)
+ else if (bodyFrame instanceof AMQResponseBody)
{
- _protocolSession.messageResponseBodyReceived(frame.channel, (AMQResponseBody)frame.bodyFrame);
+ _protocolSession.messageResponseBodyReceived(frame.getChannel(), (AMQResponseBody)bodyFrame);
}
-// if (frame.bodyFrame instanceof AMQMethodBody)
-// {
-// if (_logger.isDebugEnabled())
-// {
-// _logger.debug("Method frame received: " + frame);
-// }
-//
-// final AMQMethodEvent<AMQMethodBody> evt = new AMQMethodEvent<AMQMethodBody>(frame.channel, (AMQMethodBody) frame.bodyFrame);
-// try
-// {
-// boolean wasAnyoneInterested = false;
-// Q
-// }
-// catch (AMQException e)
-// {
-// it = _frameListeners.iterator();
-// while (it.hasNext())
-// {
-// final AMQMethodListener listener = (AMQMethodListener) it.next();
-// listener.error(e);
-// }
-// exceptionCaught(session, e);
-// }
-// }
-// else if (frame.bodyFrame instanceof ContentHeaderBody)
-// {
-// _protocolSession.messageContentHeaderReceived(frame.channel,
-// (ContentHeaderBody) frame.bodyFrame);
-// }
-// else if (frame.bodyFrame instanceof ContentBody)
-// {
-// _protocolSession.messageContentBodyReceived(frame.channel,
-// (ContentBody) frame.bodyFrame);
-// }
- else if (frame.bodyFrame instanceof HeartbeatBody)
+ else if (bodyFrame instanceof HeartbeatBody)
{
_logger.debug("Received heartbeat");
}
@@ -361,27 +337,32 @@ public class AMQProtocolHandler extends IoHandlerAdapter
public void messageSent(IoSession session, Object message) throws Exception
{
- if (_messagesOut++ % 1000 == 0)
+ final long sentMessages = _messagesOut++;
+
+ final boolean debug = _logger.isDebugEnabled();
+
+ if (debug && (sentMessages % 1000 == 0))
{
_logger.debug("Sent " + _messagesOut + " protocol messages");
}
_connection.bytesSent(session.getWrittenBytes());
- if (_logger.isDebugEnabled())
+ if (debug)
{
_logger.debug("Sent frame " + message);
}
}
- public void addFrameListener(AMQMethodListener listener)
- {
- _frameListeners.add(listener);
- }
-
- public void removeFrameListener(AMQMethodListener listener)
- {
- _frameListeners.remove(listener);
- }
+ /*
+ public void addFrameListener(AMQMethodListener listener)
+ {
+ _frameListeners.add(listener);
+ }
+ public void removeFrameListener(AMQMethodListener listener)
+ {
+ _frameListeners.remove(listener);
+ }
+ */
public void attainState(AMQState s) throws AMQException
{
getStateManager().attainState(s);
@@ -418,19 +399,36 @@ public class AMQProtocolHandler extends IoHandlerAdapter
* a particular response. Equivalent to calling getProtocolSession().write() then
* waiting for the response.
*
+ * @param channelNum
* @param methodBody
- * @param listener the blocking listener. Note the calling thread will block.
+ * @param listener The blocking listener. Note the calling thread will block.
*/
private AMQMethodEvent writeCommandFrameAndWaitForReply(int channelNum, AMQMethodBody methodBody,
BlockingMethodFrameListener listener)
throws AMQException
{
+ return writeCommandFrameAndWaitForReply(channelNum, methodBody, listener, DEFAULT_SYNC_TIMEOUT);
+ }
+
+ /**
+ * Convenience method that writes a frame to the protocol session and waits for
+ * a particular response. Equivalent to calling getProtocolSession().write() then
+ * waiting for the response.
+ *
+ * @param channelNum
+ * @param methodBody
+ * @param listener The blocking listener. Note the calling thread will block.
+ */
+ private AMQMethodEvent writeCommandFrameAndWaitForReply(int channelNum, AMQMethodBody methodBody,
+ BlockingMethodFrameListener listener, long timeout)
+ throws AMQException
+ {
try
{
_frameListeners.add(listener);
_protocolSession.writeRequest(channelNum, methodBody, listener);
- AMQMethodEvent e = listener.blockForFrame();
+ AMQMethodEvent e = listener.blockForFrame(timeout);
return e;
// When control resumes before this line, a reply will have been received
// that matches the criteria defined in the blocking listener
@@ -440,7 +438,6 @@ public class AMQProtocolHandler extends IoHandlerAdapter
// If we don't remove the listener then no-one will
_frameListeners.remove(listener);
}
-
}
/**
@@ -484,19 +481,26 @@ public class AMQProtocolHandler extends IoHandlerAdapter
{
getStateManager().changeState(AMQState.CONNECTION_CLOSING);
- // AMQP version change: Hardwire the version to 0-9 (major=0, minor=9)
- // TODO: Connect this to the session version obtained from ProtocolInitiation for this session.
// Be aware of possible changes to parameter order as versions change.
AMQMethodBody methodBody = ConnectionCloseBody.createMethodBody(
- (byte)0, (byte)9, // AMQP version (major, minor)
+ _protocolSession.getProtocolMajorVersion(), // AMQP major version
+ _protocolSession.getProtocolMinorVersion(), // AMQP minor version
0, // classId
0, // methodId
AMQConstant.REPLY_SUCCESS.getCode(), // replyCode
- "JMS client is closing the connection."); // replyText
-
- syncWrite(0, methodBody, ConnectionCloseOkBody.class);
+ new AMQShortString("JMS client is closing the connection.")); // replyText
+
+ try
+ {
+ syncWrite(0, methodBody, ConnectionCloseOkBody.class);
+ _protocolSession.closeProtocolSession();
+ }
+ catch (AMQTimeoutException e)
+ {
+ _protocolSession.closeProtocolSession(false);
+ }
+
- _protocolSession.closeProtocolSession();
}
/**
@@ -531,7 +535,7 @@ public class AMQProtocolHandler extends IoHandlerAdapter
}
}
- public String generateQueueName()
+ public AMQShortString generateQueueName()
{
return _protocolSession.generateQueueName();
}
@@ -567,7 +571,7 @@ public class AMQProtocolHandler extends IoHandlerAdapter
return _protocolSession;
}
- FailoverState getFailoverState()
+ public FailoverState getFailoverState()
{
return _failoverState;
}
@@ -577,8 +581,18 @@ public class AMQProtocolHandler extends IoHandlerAdapter
_failoverState = failoverState;
}
- public int getConnectionId()
+ public long getConnectionId()
{
return _connection.getConnectionId();
}
+
+ public byte getProtocolMajorVersion()
+ {
+ return _protocolSession.getProtocolMajorVersion();
+ }
+
+ public byte getProtocolMinorVersion()
+ {
+ return _protocolSession.getProtocolMinorVersion();
+ }
}
diff --git a/java/client/src/main/java/org/apache/qpid/client/protocol/AMQProtocolSession.java b/java/client/src/main/java/org/apache/qpid/client/protocol/AMQProtocolSession.java
index de5cd4821d..77ecd1f4c0 100644
--- a/java/client/src/main/java/org/apache/qpid/client/protocol/AMQProtocolSession.java
+++ b/java/client/src/main/java/org/apache/qpid/client/protocol/AMQProtocolSession.java
@@ -37,28 +37,32 @@ import org.apache.qpid.client.AMQConnection;
import org.apache.qpid.client.AMQSession;
import org.apache.qpid.client.ConnectionTuneParameters;
import org.apache.qpid.client.message.UnprocessedMessage;
-import org.apache.qpid.client.state.AMQStateManager;
import org.apache.qpid.framing.AMQDataBlock;
import org.apache.qpid.framing.AMQMethodBody;
import org.apache.qpid.framing.AMQRequestBody;
import org.apache.qpid.framing.AMQResponseBody;
+import org.apache.qpid.framing.AMQShortString;
+import org.apache.qpid.framing.MainRegistry;
import org.apache.qpid.framing.MessageAppendBody;
import org.apache.qpid.framing.ProtocolInitiation;
import org.apache.qpid.framing.ProtocolVersionList;
import org.apache.qpid.framing.RequestManager;
import org.apache.qpid.framing.RequestResponseMappingException;
import org.apache.qpid.framing.ResponseManager;
+import org.apache.qpid.framing.VersionSpecificRegistry;
import org.apache.qpid.protocol.AMQMethodEvent;
import org.apache.qpid.protocol.AMQMethodListener;
import org.apache.qpid.protocol.AMQProtocolWriter;
+import org.apache.qpid.protocol.AMQVersionAwareProtocolSession;
+import org.apache.qpid.client.state.AMQStateManager;
/**
* Wrapper for protocol session that provides type-safe access to session attributes.
- *
+ * <p/>
* The underlying protocol session is still available but clients should not
* use it to obtain session attributes.
*/
-public class AMQProtocolSession implements AMQProtocolWriter, ProtocolVersionList
+public class AMQProtocolSession implements ProtocolVersionList, AMQVersionAwareProtocolSession
{
protected static final int LAST_WRITE_FUTURE_JOIN_TIMEOUT = 1000 * 60 * 2;
@@ -107,7 +111,12 @@ public class AMQProtocolSession implements AMQProtocolWriter, ProtocolVersionLis
protected int _queueId = 1;
protected final Object _queueIdLock = new Object();
- protected int _ConnectionId;
+ protected long _ConnectionId;
+
+ private byte _protocolMinorVersion;
+ private byte _protocolMajorVersion;
+ private VersionSpecificRegistry _registry = MainRegistry.getVersionSpecificRegistry(pv[pv.length-1][PROTOCOL_MAJOR],pv[pv.length-1][PROTOCOL_MINOR]);
+
/**
* No-arg constructor for use by test subclass - has to initialise final vars
@@ -130,6 +139,8 @@ public class AMQProtocolSession implements AMQProtocolWriter, ProtocolVersionLis
_protocolHandler = protocolHandler;
_minaProtocolSession = protocolSession;
// properties of the connection are made available to the event handlers
+ _minaProtocolSession.setWriteTimeout(LAST_WRITE_FUTURE_JOIN_TIMEOUT);
+ //fixme - real value needed
_minaProtocolSession.setAttribute(AMQ_CONNECTION, connection);
_stateManager = new AMQStateManager(this);
@@ -143,6 +154,7 @@ public class AMQProtocolSession implements AMQProtocolWriter, ProtocolVersionLis
{
_protocolHandler = protocolHandler;
_minaProtocolSession = protocolSession;
+ _minaProtocolSession.setAttachment(this);
// properties of the connection are made available to the event handlers
_minaProtocolSession.setAttribute(AMQ_CONNECTION, connection);
@@ -221,8 +233,9 @@ public class AMQProtocolSession implements AMQProtocolWriter, ProtocolVersionLis
/**
* Store the SASL client currently being used for the authentication handshake
+ *
* @param client if non-null, stores this in the session. if null clears any existing client
- * being stored
+ * being stored
*/
public void setSaslClient(SaslClient client)
{
@@ -253,6 +266,7 @@ public class AMQProtocolSession implements AMQProtocolWriter, ProtocolVersionLis
/**
* This is involed from MessageTransferMethodHandler if type is CONTENT_TYPE_REFERENCE
* This is invoked on the MINA dispatcher thread.
+ *
* @param message
* @throws AMQException if this was not expected
*/
@@ -296,13 +310,14 @@ public class AMQProtocolSession implements AMQProtocolWriter, ProtocolVersionLis
* This is involed from MessageTransferMethodHandler if type is CONTENT_TYPE_INLINE
* Deliver a message to the appropriate session, removing the unprocessed message
* from our map
+ *
* @param channelId the channel id the message should be delivered to
- * @param msg the message
+ * @param msg the message
*/
public void deliverMessageToAMQSession(int channelId, UnprocessedMessage msg)
{
AMQSession session = (AMQSession) _channelId2SessionMap.get(channelId);
- msg.contentHeader.setSize(msg.bytesReceived);
+ msg.getMessageHeaders().setSize(msg.getBytesReceived());
session.messageReceived(msg);
}
@@ -360,6 +375,7 @@ public class AMQProtocolSession implements AMQProtocolWriter, ProtocolVersionLis
WriteFuture f = _minaProtocolSession.write(frame);
if (wait)
{
+ //fixme -- time out?
f.join();
}
else
@@ -404,6 +420,7 @@ public class AMQProtocolSession implements AMQProtocolWriter, ProtocolVersionLis
/**
* Starts the process of closing a session
+ *
* @param session the AMQSession being closed
*/
public void closeSession(AMQSession session)
@@ -425,19 +442,27 @@ public class AMQProtocolSession implements AMQProtocolWriter, ProtocolVersionLis
* This method decides whether this is a response or an initiation. The latter
* case causes the AMQSession to be closed and an exception to be thrown if
* appropriate.
+ *
* @param channelId the id of the channel (session)
* @return true if the client must respond to the server, i.e. if the server
- * initiated the channel close, false if the channel close is just the server
- * responding to the client's earlier request to close the channel.
+ * initiated the channel close, false if the channel close is just the server
+ * responding to the client's earlier request to close the channel.
*/
- public boolean channelClosed(int channelId, int code, String text)
+ public boolean channelClosed(int channelId, int code, String text) throws AMQException
{
final Integer chId = channelId;
// if this is not a response to an earlier request to close the channel
if (_closingChannels.remove(chId) == null)
{
final AMQSession session = (AMQSession) _channelId2SessionMap.get(chId);
- session.closed(new AMQException(_logger, code, text));
+ try
+ {
+ session.closed(new AMQException(_logger, code, text));
+ }
+ catch (JMSException e)
+ {
+ throw new AMQException("JMSException received while closing session", e);
+ }
return true;
}
else
@@ -453,15 +478,20 @@ public class AMQProtocolSession implements AMQProtocolWriter, ProtocolVersionLis
public void closeProtocolSession()
{
+ closeProtocolSession(true);
+ }
+
+ public void closeProtocolSession(boolean waitLast)
+ {
_logger.debug("Waiting for last write to join.");
- if (_lastWriteFuture != null)
+ if (waitLast && _lastWriteFuture != null)
{
_lastWriteFuture.join(LAST_WRITE_FUTURE_JOIN_TIMEOUT);
}
_logger.debug("Closing protocol session");
final CloseFuture future = _minaProtocolSession.close();
- future.join();
+ future.join(LAST_WRITE_FUTURE_JOIN_TIMEOUT);
}
public void failover(String host, int port)
@@ -469,20 +499,19 @@ public class AMQProtocolSession implements AMQProtocolWriter, ProtocolVersionLis
_protocolHandler.failover(host, port);
}
- protected String generateQueueName()
+ protected AMQShortString generateQueueName()
{
int id;
- synchronized(_queueIdLock)
+ synchronized (_queueIdLock)
{
id = _queueId++;
}
//get rid of / and : and ; from address for spec conformance
- String localAddress = StringUtils.replaceChars(_minaProtocolSession.getLocalAddress().toString(),"/;:","");
- return "tmp_" + localAddress + "_" + id;
+ String localAddress = StringUtils.replaceChars(_minaProtocolSession.getLocalAddress().toString(), "/;:", "");
+ return new AMQShortString("tmp_" + localAddress + "_" + id);
}
/**
- *
* @param delay delay in seconds (not ms)
*/
void initHeartbeats(int delay)
@@ -495,11 +524,39 @@ public class AMQProtocolSession implements AMQProtocolWriter, ProtocolVersionLis
}
}
- public void confirmConsumerCancelled(int channelId, String consumerTag)
+ public void confirmConsumerCancelled(int channelId, AMQShortString consumerTag)
{
final Integer chId = channelId;
final AMQSession session = (AMQSession) _channelId2SessionMap.get(chId);
session.confirmConsumerCancelled(consumerTag);
}
+
+ public void setProtocolVersion(final byte versionMajor, final byte versionMinor)
+ {
+ _protocolMajorVersion = versionMajor;
+ _protocolMinorVersion = versionMinor;
+ _registry = MainRegistry.getVersionSpecificRegistry(versionMajor, versionMinor);
+ }
+
+ public byte getProtocolMinorVersion()
+ {
+ return _protocolMinorVersion;
+ }
+
+ public byte getProtocolMajorVersion()
+ {
+ return _protocolMajorVersion;
+ }
+
+ public boolean isProtocolVersionEqual(byte major, byte minor)
+ {
+ return _protocolMinorVersion == major && _protocolMajorVersion == minor;
+ }
+
+ public VersionSpecificRegistry getRegistry()
+ {
+ return _registry;
+ }
+
}
diff --git a/java/client/src/main/java/org/apache/qpid/client/protocol/BlockingMethodFrameListener.java b/java/client/src/main/java/org/apache/qpid/client/protocol/BlockingMethodFrameListener.java
index c05e6faf53..ff38b96e63 100644
--- a/java/client/src/main/java/org/apache/qpid/client/protocol/BlockingMethodFrameListener.java
+++ b/java/client/src/main/java/org/apache/qpid/client/protocol/BlockingMethodFrameListener.java
@@ -21,10 +21,13 @@
package org.apache.qpid.client.protocol;
import org.apache.qpid.AMQException;
+import org.apache.qpid.AMQDisconnectedException;
+import org.apache.qpid.AMQTimeoutException;
import org.apache.qpid.framing.AMQMethodBody;
import org.apache.qpid.protocol.AMQMethodEvent;
import org.apache.qpid.protocol.AMQMethodListener;
import org.apache.qpid.client.protocol.AMQProtocolSession;
+import org.apache.qpid.client.failover.FailoverException;
public abstract class BlockingMethodFrameListener implements AMQMethodListener
{
@@ -52,6 +55,7 @@ public abstract class BlockingMethodFrameListener implements AMQMethodListener
/**
* This method is called by the MINA dispatching thread. Note that it could
* be called before blockForFrame() has been called.
+ *
* @param evt the frame event
* @return true if the listener has dealt with this frame
* @throws AMQException
@@ -89,7 +93,7 @@ public abstract class BlockingMethodFrameListener implements AMQMethodListener
/**
* This method is called by the thread that wants to wait for a frame.
*/
- public AMQMethodEvent blockForFrame() throws AMQException
+ public AMQMethodEvent blockForFrame(long timeout) throws AMQException
{
synchronized (_lock)
{
@@ -97,11 +101,29 @@ public abstract class BlockingMethodFrameListener implements AMQMethodListener
{
try
{
- _lock.wait();
+ if (timeout == -1)
+ {
+ _lock.wait();
+ }
+ else
+ {
+
+ _lock.wait(timeout);
+ if (!_ready)
+ {
+ _error = new AMQTimeoutException("Server did not respond in a timely fashion");
+ _ready = true;
+ }
+ }
}
catch (InterruptedException e)
{
- // IGNORE
+ // IGNORE -- //fixme this isn't ideal as being interrupted isn't equivellant to sucess
+// if (!_ready && timeout != -1)
+// {
+// _error = new AMQException("Server did not respond timely");
+// _ready = true;
+// }
}
}
}
@@ -109,11 +131,16 @@ public abstract class BlockingMethodFrameListener implements AMQMethodListener
{
if (_error instanceof AMQException)
{
- throw (AMQException)_error;
+ throw(AMQException) _error;
+ }
+ else if (_error instanceof FailoverException)
+ {
+ // This should ensure that FailoverException is not wrapped and can be caught.
+ throw(FailoverException) _error; // needed to expose FailoverException.
}
else
{
- throw new AMQException("Woken up due to " + _error.getClass(), _error); // FIXME: This will wrap FailoverException and prevent it being caught.
+ throw new AMQException("Woken up due to " + _error.getClass(), _error);
}
}
@@ -123,6 +150,7 @@ public abstract class BlockingMethodFrameListener implements AMQMethodListener
/**
* This is a callback, called by the MINA dispatcher thread only. It is also called from within this
* class to avoid code repetition but again is only called by the MINA dispatcher thread.
+ *
* @param e
*/
public void error(Exception e)
diff --git a/java/client/src/main/java/org/apache/qpid/client/security/amqplain/AmqPlainSaslClient.java b/java/client/src/main/java/org/apache/qpid/client/security/amqplain/AmqPlainSaslClient.java
index 4291cb3259..ddbea9a557 100644
--- a/java/client/src/main/java/org/apache/qpid/client/security/amqplain/AmqPlainSaslClient.java
+++ b/java/client/src/main/java/org/apache/qpid/client/security/amqplain/AmqPlainSaslClient.java
@@ -73,8 +73,8 @@ public class AmqPlainSaslClient implements SaslClient
throw new SaslException("Error handling SASL callbacks: " + e, e);
}
FieldTable table = FieldTableFactory.newFieldTable();
- table.put("LOGIN", nameCallback.getName());
- table.put("PASSWORD", pwdCallback.getPassword());
+ table.setString("LOGIN", nameCallback.getName());
+ table.setString("PASSWORD", new String(pwdCallback.getPassword()));
return table.getDataAsBytes();
}
diff --git a/java/client/src/main/java/org/apache/qpid/client/state/AMQStateManager.java b/java/client/src/main/java/org/apache/qpid/client/state/AMQStateManager.java
index 5ace6dde69..e268cabf6c 100644
--- a/java/client/src/main/java/org/apache/qpid/client/state/AMQStateManager.java
+++ b/java/client/src/main/java/org/apache/qpid/client/state/AMQStateManager.java
@@ -55,11 +55,15 @@ public class AMQStateManager implements AMQMethodListener
private final Map _state2HandlersMap = new HashMap();
private final CopyOnWriteArraySet _stateListeners = new CopyOnWriteArraySet();
-
+
+ private final Object _stateLock = new Object();
+ private static final long MAXIMUM_STATE_WAIT_TIME = 30000l;
+
public AMQStateManager()
{
this(null);
}
+
public AMQStateManager(AMQProtocolSession protocolSession)
{
@@ -133,17 +137,11 @@ public class AMQStateManager implements AMQMethodListener
public void changeState(AMQState newState) throws AMQException
{
_logger.debug("State changing to " + newState + " from old state " + _currentState);
- final AMQState oldState = _currentState;
- _currentState = newState;
- synchronized (_stateListeners)
+ synchronized (_stateLock)
{
- final Iterator it = _stateListeners.iterator();
- while (it.hasNext())
- {
- final StateListener l = (StateListener) it.next();
- l.stateChanged(oldState, newState);
- }
+ _currentState = newState;
+ _stateLock.notifyAll();
}
}
@@ -161,7 +159,7 @@ public class AMQStateManager implements AMQMethodListener
}
}
- public boolean methodReceived(AMQMethodEvent evt) throws AMQException
+ public <B extends AMQMethodBody> boolean methodReceived(AMQMethodEvent<B> evt) throws AMQException
{
StateAwareMethodListener handler = findStateTransitionHandler(_currentState, evt.getMethod());
if (handler != null)
@@ -210,36 +208,35 @@ public class AMQStateManager implements AMQMethodListener
}
}
- public void addStateListener(StateListener listener)
- {
- _logger.debug("Adding state listener");
- _stateListeners.add(listener);
- }
-
- public void removeStateListener(StateListener listener)
- {
- _stateListeners.remove(listener);
- }
- public void attainState(AMQState s) throws AMQException
+ public void attainState(final AMQState s) throws AMQException
{
- boolean needToWait = false;
- StateWaiter sw = null;
- synchronized (_stateListeners)
+ synchronized(_stateLock)
{
- if (_currentState != s)
+ final long waitUntilTime = System.currentTimeMillis() + MAXIMUM_STATE_WAIT_TIME;
+ long waitTime = MAXIMUM_STATE_WAIT_TIME;
+
+ while(_currentState != s && waitTime > 0)
{
- _logger.debug("Adding state wait to reach state " + s);
- sw = new StateWaiter(s);
- addStateListener(sw);
- // we use a boolean since we must release the lock before starting to wait
- needToWait = true;
+ try
+ {
+ _stateLock.wait(MAXIMUM_STATE_WAIT_TIME);
+ }
+ catch (InterruptedException e)
+ {
+ _logger.warn("Thread interrupted");
+ }
+ if(_currentState != s)
+ {
+ waitTime = waitUntilTime - System.currentTimeMillis();
+ }
+ }
+ if(_currentState != s)
+ {
+ throw new AMQException("State not achieved within permitted time. Current state " + _currentState + ", desired state: " + s);
}
}
- if (needToWait)
- {
- sw.waituntilStateHasChanged();
- }
+
// at this point the state will have changed.
}
diff --git a/java/client/src/main/java/org/apache/qpid/client/state/StateWaiter.java b/java/client/src/main/java/org/apache/qpid/client/state/StateWaiter.java
index 18e1fdad82..b2940d73ae 100644
--- a/java/client/src/main/java/org/apache/qpid/client/state/StateWaiter.java
+++ b/java/client/src/main/java/org/apache/qpid/client/state/StateWaiter.java
@@ -25,7 +25,6 @@ import org.apache.qpid.AMQException;
/**
* Waits for a particular state to be reached.
- *
*/
public class StateWaiter implements StateListener
{
@@ -38,6 +37,7 @@ public class StateWaiter implements StateListener
private volatile Throwable _throwable;
private final Object _monitor = new Object();
+ private static final long TIME_OUT = 1000 * 60 * 2;
public StateWaiter(AMQState state)
{
@@ -46,7 +46,7 @@ public class StateWaiter implements StateListener
public void waituntilStateHasChanged() throws AMQException
{
- synchronized(_monitor)
+ synchronized (_monitor)
{
//
// The guard is required in case we are woken up by a spurious
@@ -57,7 +57,7 @@ public class StateWaiter implements StateListener
try
{
_logger.debug("State " + _state + " not achieved so waiting...");
- _monitor.wait();
+ _monitor.wait(TIME_OUT);
}
catch (InterruptedException e)
{
@@ -82,7 +82,7 @@ public class StateWaiter implements StateListener
public void stateChanged(AMQState oldState, AMQState newState)
{
- synchronized(_monitor)
+ synchronized (_monitor)
{
if (_logger.isDebugEnabled())
{
@@ -103,7 +103,7 @@ public class StateWaiter implements StateListener
public void error(Throwable t)
{
- synchronized(_monitor)
+ synchronized (_monitor)
{
if (_logger.isDebugEnabled())
{
diff --git a/java/client/src/main/java/org/apache/qpid/client/transport/SocketTransportConnection.java b/java/client/src/main/java/org/apache/qpid/client/transport/SocketTransportConnection.java
index d6364f45b0..5e6244d7cc 100644
--- a/java/client/src/main/java/org/apache/qpid/client/transport/SocketTransportConnection.java
+++ b/java/client/src/main/java/org/apache/qpid/client/transport/SocketTransportConnection.java
@@ -71,7 +71,7 @@ public class SocketTransportConnection implements ITransportConnection
boolean readWriteThreading = Boolean.getBoolean("amqj.shared_read_write_pool");
if (readWriteThreading)
{
- cfg.setThreadModel(new ReadWriteThreadModel());
+ cfg.setThreadModel(ReadWriteThreadModel.getInstance());
}
SocketSessionConfig scfg = (SocketSessionConfig) cfg.getSessionConfig();
diff --git a/java/client/src/main/java/org/apache/qpid/client/transport/TransportConnection.java b/java/client/src/main/java/org/apache/qpid/client/transport/TransportConnection.java
index e9e23aefdb..99a4c5f30d 100644
--- a/java/client/src/main/java/org/apache/qpid/client/transport/TransportConnection.java
+++ b/java/client/src/main/java/org/apache/qpid/client/transport/TransportConnection.java
@@ -70,7 +70,7 @@ public class TransportConnection
IoServiceConfig config = _acceptor.getDefaultConfig();
- config.setThreadModel(new ReadWriteThreadModel());
+ config.setThreadModel(ReadWriteThreadModel.getInstance());
}
public static ITransportConnection getInstance() throws AMQTransportConnectionException
diff --git a/java/client/src/main/java/org/apache/qpid/client/transport/VmPipeTransportConnection.java b/java/client/src/main/java/org/apache/qpid/client/transport/VmPipeTransportConnection.java
index 1fc43f3496..a2189ba248 100644
--- a/java/client/src/main/java/org/apache/qpid/client/transport/VmPipeTransportConnection.java
+++ b/java/client/src/main/java/org/apache/qpid/client/transport/VmPipeTransportConnection.java
@@ -49,10 +49,10 @@ public class VmPipeTransportConnection implements ITransportConnection
final VmPipeConnector ioConnector = new VmPipeConnector();
final IoServiceConfig cfg = ioConnector.getDefaultConfig();
ReferenceCountingExecutorService executorService = ReferenceCountingExecutorService.getInstance();
- PoolingFilter asyncRead = new PoolingFilter(executorService, PoolingFilter.READ_EVENTS,
+ PoolingFilter asyncRead = PoolingFilter.createAynschReadPoolingFilter(executorService,
"AsynchronousReadFilter");
cfg.getFilterChain().addFirst("AsynchronousReadFilter", asyncRead);
- PoolingFilter asyncWrite = new PoolingFilter(executorService, PoolingFilter.WRITE_EVENTS,
+ PoolingFilter asyncWrite = PoolingFilter.createAynschWritePoolingFilter(executorService,
"AsynchronousWriteFilter");
cfg.getFilterChain().addLast("AsynchronousWriteFilter", asyncWrite);
diff --git a/java/client/src/main/java/org/apache/qpid/jndi/PropertiesFileInitialContextFactory.java b/java/client/src/main/java/org/apache/qpid/jndi/PropertiesFileInitialContextFactory.java
index 5497cafed4..c6d6731967 100644
--- a/java/client/src/main/java/org/apache/qpid/jndi/PropertiesFileInitialContextFactory.java
+++ b/java/client/src/main/java/org/apache/qpid/jndi/PropertiesFileInitialContextFactory.java
@@ -29,6 +29,7 @@ import org.apache.qpid.client.AMQDestination;
import org.apache.qpid.url.AMQBindingURL;
import org.apache.qpid.url.BindingURL;
import org.apache.qpid.url.URLSyntaxException;
+import org.apache.qpid.framing.AMQShortString;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
@@ -63,7 +64,7 @@ public class PropertiesFileInitialContextFactory implements InitialContextFactor
{
String file = null;
- if (environment.contains(Context.PROVIDER_URL))
+ if (environment.containsKey(Context.PROVIDER_URL))
{
file = (String) environment.get(Context.PROVIDER_URL);
}
@@ -85,7 +86,7 @@ public class PropertiesFileInitialContextFactory implements InitialContextFactor
}
else
{
- _logger.warn("No Provider URL specified.");
+ _logger.info("No Provider URL specified.");
}
}
catch (IOException ioe)
@@ -232,10 +233,14 @@ public class PropertiesFileInitialContextFactory implements InitialContextFactor
*/
protected Queue createQueue(Object value)
{
- if (value instanceof String)
+ if(value instanceof AMQShortString)
+ {
+ return new AMQQueue((AMQShortString) value);
+ }
+ else if (value instanceof String)
{
- return new AMQQueue((String) value);
+ return new AMQQueue(new AMQShortString((String) value));
}
else if (value instanceof BindingURL)
@@ -251,9 +256,13 @@ public class PropertiesFileInitialContextFactory implements InitialContextFactor
*/
protected Topic createTopic(Object value)
{
- if (value instanceof String)
+ if(value instanceof AMQShortString)
+ {
+ return new AMQTopic((AMQShortString)value);
+ }
+ else if (value instanceof String)
{
- return new AMQTopic((String) value);
+ return new AMQTopic(new AMQShortString((String) value));
}
else if (value instanceof BindingURL)
diff --git a/java/client/src/old_test/java/org/apache/qpid/codec/BasicDeliverTest.java b/java/client/src/old_test/java/org/apache/qpid/codec/BasicDeliverTest.java
index 892b349cea..1db7e200bd 100644
--- a/java/client/src/old_test/java/org/apache/qpid/codec/BasicDeliverTest.java
+++ b/java/client/src/old_test/java/org/apache/qpid/codec/BasicDeliverTest.java
@@ -7,9 +7,9 @@
* 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
@@ -64,15 +64,21 @@ public class BasicDeliverTest
long min = Long.MAX_VALUE;
long max = 0;
long total = 0;
- for(int i = 0; i < iterations; i++)
+ for (int i = 0; i < iterations; i++)
{
long time = decode(size, count);
total += time;
- if(time < min) min = time;
- if(time > max) max = time;
+ if (time < min)
+ {
+ min = time;
+ }
+ if (time > max)
+ {
+ max = time;
+ }
}
System.out.println("Decoded " + count + " messages of " + size +
- " bytes: avg=" + (total / iterations) + ", min=" + min + ", max=" + max) ;
+ " bytes: avg=" + (total / iterations) + ", min=" + min + ", max=" + max);
}
@@ -84,7 +90,7 @@ public class BasicDeliverTest
data.flip();
AMQDecoder decoder = new AMQDecoder(false);
long start = System.currentTimeMillis();
- for(int i = 0; i < count; i++)
+ for (int i = 0; i < count; i++)
{
decoder.decode(session, data, decoderOutput);
data.rewind();
@@ -97,15 +103,21 @@ public class BasicDeliverTest
long min = Long.MAX_VALUE;
long max = 0;
long total = 0;
- for(int i = 0; i < iterations; i++)
+ for (int i = 0; i < iterations; i++)
{
long time = encode(size, count);
total += time;
- if(time < min) min = time;
- if(time > max) max = time;
+ if (time < min)
+ {
+ min = time;
+ }
+ if (time > max)
+ {
+ max = time;
+ }
}
System.out.println("Encoded " + count + " messages of " + size +
- " bytes: avg=" + (total / iterations) + ", min=" + min + ", max=" + max) ;
+ " bytes: avg=" + (total / iterations) + ", min=" + min + ", max=" + max);
}
long encode(int size, int count) throws Exception
@@ -114,14 +126,15 @@ public class BasicDeliverTest
AMQDataBlock block = getDataBlock(size);
AMQEncoder encoder = new AMQEncoder();
long start = System.currentTimeMillis();
- for(int i = 0; i < count; i++)
+ for (int i = 0; i < count; i++)
{
encoder.encode(session, block, encoderOutput);
}
return System.currentTimeMillis() - start;
}
- private final ProtocolEncoderOutput encoderOutput = new ProtocolEncoderOutput(){
+ private final ProtocolEncoderOutput encoderOutput = new ProtocolEncoderOutput()
+ {
public void write(ByteBuffer byteBuffer)
{
@@ -137,7 +150,8 @@ public class BasicDeliverTest
}
};
- private final ProtocolDecoderOutput decoderOutput = new ProtocolDecoderOutput(){
+ private final ProtocolDecoderOutput decoderOutput = new ProtocolDecoderOutput()
+ {
public void write(Object object)
{
}
@@ -147,7 +161,8 @@ public class BasicDeliverTest
}
};
- private final IoSession session = new BaseIoSession(){
+ private final IoSession session = new BaseIoSession()
+ {
protected void updateTrafficMask()
{
@@ -216,19 +231,16 @@ public class BasicDeliverTest
{
//create a frame representing message delivery
AMQFrame[] frames = new AMQFrame[3];
- frames[0] = wrapBody( createBasicDeliverBody() );
- frames[1] = wrapBody( createContentHeaderBody() );
- frames[2] = wrapBody( createContentBody(size) );
+ frames[0] = wrapBody(createBasicDeliverBody());
+ frames[1] = wrapBody(createContentHeaderBody());
+ frames[2] = wrapBody(createContentBody(size));
return new CompositeAMQDataBlock(frames);
}
static AMQFrame wrapBody(AMQBody body)
{
- AMQFrame frame = new AMQFrame();
- frame.bodyFrame = body;
- frame.channel = 1;
-
+ AMQFrame frame = new AMQFrame(1, body);
return frame;
}
@@ -236,7 +248,7 @@ public class BasicDeliverTest
{
ContentBody body = new ContentBody();
body.payload = ByteBuffer.allocate(size);
- for(int i = 0; i < size; i++)
+ for (int i = 0; i < size; i++)
{
body.payload.put((byte) DATA[i % DATA.length]);
}
@@ -254,12 +266,12 @@ public class BasicDeliverTest
static BasicDeliverBody createBasicDeliverBody()
{
- BasicDeliverBody body = new BasicDeliverBody();
- body.consumerTag = "myConsumerTag";
- body.deliveryTag = 1;
- body.exchange = "myExchange";
- body.redelivered = false;
- body.routingKey = "myRoutingKey";
+ BasicDeliverBody body = new BasicDeliverBody((byte) 8, (byte) 0,
+ BasicDeliverBody.getClazz((byte) 8, (byte) 0),
+ BasicDeliverBody.getMethod((byte) 8, (byte) 0),
+ new AMQShortString("myConsumerTag"), 1,
+ new AMQShortString("myExchange"), false,
+ new AMQShortString("myRoutingKey"));
return body;
}
}
diff --git a/java/client/src/old_test/java/org/apache/qpid/codec/Client.java b/java/client/src/old_test/java/org/apache/qpid/codec/Client.java
index c0de5ab133..3886021277 100644
--- a/java/client/src/old_test/java/org/apache/qpid/codec/Client.java
+++ b/java/client/src/old_test/java/org/apache/qpid/codec/Client.java
@@ -106,12 +106,12 @@ public class Client extends IoHandlerAdapter
private static boolean isDeliver(Object o)
{
- return o instanceof AMQFrame && ((AMQFrame) o).bodyFrame instanceof BasicDeliverBody;
+ return o instanceof AMQFrame && ((AMQFrame) o).getBodyFrame() instanceof BasicDeliverBody;
}
private static boolean isContent(Object o)
{
- return o instanceof AMQFrame && ((AMQFrame) o).bodyFrame instanceof ContentBody;
+ return o instanceof AMQFrame && ((AMQFrame) o).getBodyFrame() instanceof ContentBody;
}
public static void main(String[] argv) throws Exception
diff --git a/java/client/src/old_test/java/org/apache/qpid/framing/FieldTableTest.java b/java/client/src/old_test/java/org/apache/qpid/framing/FieldTableTest.java
index 2a7cb8be30..955f82fab5 100644
--- a/java/client/src/old_test/java/org/apache/qpid/framing/FieldTableTest.java
+++ b/java/client/src/old_test/java/org/apache/qpid/framing/FieldTableTest.java
@@ -7,9 +7,9 @@
* 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
@@ -20,6 +20,7 @@
*/
package org.apache.qpid.framing;
+import junit.framework.TestCase;
import org.apache.mina.common.ByteBuffer;
import java.io.BufferedReader;
@@ -29,8 +30,6 @@ import java.io.Reader;
import java.util.Enumeration;
import java.util.Properties;
-import junit.framework.TestCase;
-
public class FieldTableTest extends TestCase
{
@@ -40,17 +39,17 @@ public class FieldTableTest extends TestCase
String key = "String";
String value = "Hello";
- table.put(key, value);
+ table.setString(key, value);
//Add one for the type encoding
int size = EncodingUtils.encodedShortStringLength(key) + 1 +
EncodingUtils.encodedLongStringLength(value);
assertEquals(table.getEncodedSize(), size);
-
+
key = "Integer";
Integer number = new Integer(60);
- table.put(key, number);
+ table.setInteger(key, number);
//Add one for the type encoding
size += EncodingUtils.encodedShortStringLength(key) + 1 + 4;
@@ -87,22 +86,22 @@ public class FieldTableTest extends TestCase
doTestEncoding(load("FieldTableTest2.properties"));
}
*/
- void doTestEncoding(FieldTable table) throws AMQFrameDecodingException
+ void doTestEncoding(FieldTable table) throws AMQFrameDecodingException, AMQProtocolVersionException
{
assertEquivalent(table, encodeThenDecode(table));
}
public void assertEquivalent(FieldTable table1, FieldTable table2)
{
- for (Object o : table1.keySet())
+ for (String key : table1.keys())
{
- String key = (String) o;
- assertEquals("Values for " + key + " did not match", table1.get(key), table2.get(key));
+
+ assertEquals("Values for " + key + " did not match", table1.getObject(key), table2.getObject(key));
//System.out.println("Values for " + key + " matched (" + table1.get(key) + ")");
}
}
- FieldTable encodeThenDecode(FieldTable table) throws AMQFrameDecodingException
+ FieldTable encodeThenDecode(FieldTable table) throws AMQFrameDecodingException, AMQProtocolVersionException
{
ContentHeaderBody header = new ContentHeaderBody();
header.classId = 6;
@@ -153,11 +152,11 @@ public class FieldTableTest extends TestCase
try
{
int ival = Integer.parseInt(value);
- table.put(key, (long) ival);
+ table.setLong(key, (long) ival);
}
catch (NumberFormatException e)
{
- table.put(key, value);
+ table.setObject(key, value);
}
}
return table;
diff --git a/java/client/src/old_test/java/org/apache/qpid/headers/Listener.java b/java/client/src/old_test/java/org/apache/qpid/headers/Listener.java
index d97fc22a35..cb5caefc1e 100644
--- a/java/client/src/old_test/java/org/apache/qpid/headers/Listener.java
+++ b/java/client/src/old_test/java/org/apache/qpid/headers/Listener.java
@@ -23,7 +23,7 @@ package org.apache.qpid.headers;
import org.apache.qpid.client.AMQConnection;
import org.apache.qpid.client.AMQSession;
import org.apache.qpid.jms.Session;
-import org.apache.qpid.testutil.Config;
+//import org.apache.qpid.testutil.Config;
import javax.jms.MessageListener;
import javax.jms.Message;
@@ -31,9 +31,9 @@ import javax.jms.Destination;
import javax.jms.MessageProducer;
import javax.jms.JMSException;
-public class Listener implements MessageListener
+public class Listener //implements MessageListener
{
- private final AMQConnection _connection;
+/* private final AMQConnection _connection;
private final MessageProducer _controller;
private final AMQSession _session;
private final MessageFactory _factory;
@@ -113,5 +113,5 @@ public class Listener implements MessageListener
config.setName("test_headers_exchange");
config.setOptions(argv);
new Listener((AMQConnection) config.getConnection(), config.getDestination());
- }
+ }*/
}
diff --git a/java/client/src/old_test/java/org/apache/qpid/headers/MessageFactory.java b/java/client/src/old_test/java/org/apache/qpid/headers/MessageFactory.java
index 6f538d068c..a2d575fdd4 100644
--- a/java/client/src/old_test/java/org/apache/qpid/headers/MessageFactory.java
+++ b/java/client/src/old_test/java/org/apache/qpid/headers/MessageFactory.java
@@ -129,14 +129,14 @@ class MessageFactory
FieldTable getConsumerBinding()
{
FieldTable binding = FieldTableFactory.newFieldTable();
- binding.put("SF0000", "value");
+ binding.setString("SF0000", "value");
return binding;
}
FieldTable getControllerBinding()
{
FieldTable binding = FieldTableFactory.newFieldTable();
- binding.put("SCONTROL", "value");
+ binding.setString("SCONTROL", "value");
return binding;
}
diff --git a/java/client/src/old_test/java/org/apache/qpid/headers/Publisher.java b/java/client/src/old_test/java/org/apache/qpid/headers/Publisher.java
index a4ac5f670d..d9ef702c48 100644
--- a/java/client/src/old_test/java/org/apache/qpid/headers/Publisher.java
+++ b/java/client/src/old_test/java/org/apache/qpid/headers/Publisher.java
@@ -22,13 +22,13 @@ package org.apache.qpid.headers;
import org.apache.qpid.client.AMQConnection;
import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.testutil.Config;
+//import org.apache.qpid.testutil.Config;
import javax.jms.*;
-public class Publisher implements MessageListener
+public class Publisher // implements MessageListener
{
- private final Object _lock = new Object();
+/* private final Object _lock = new Object();
private final AMQConnection _connection;
private final AMQSession _session;
private final Destination _exchange;
@@ -129,5 +129,5 @@ public class Publisher implements MessageListener
new Publisher(config).test(msgCount, consumerCount);
}
- }
+ }*/
}
diff --git a/java/client/src/old_test/java/org/apache/qpid/mina/AcceptorTest.java b/java/client/src/old_test/java/org/apache/qpid/mina/AcceptorTest.java
index de3d558f7c..f0ac0e6902 100644
--- a/java/client/src/old_test/java/org/apache/qpid/mina/AcceptorTest.java
+++ b/java/client/src/old_test/java/org/apache/qpid/mina/AcceptorTest.java
@@ -82,7 +82,7 @@ public class AcceptorTest extends TestCase
sc.setSendBufferSize(32768);
sc.setReceiveBufferSize(32768);
- config.setThreadModel(new ReadWriteThreadModel());
+ config.setThreadModel(ReadWriteThreadModel.getInstance());
acceptor.bind(new InetSocketAddress(PORT),
new TestHandler());
diff --git a/java/client/src/old_test/java/org/apache/qpid/ping/TestPingClient.java b/java/client/src/old_test/java/org/apache/qpid/ping/TestPingClient.java
deleted file mode 100644
index b060498d9b..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/ping/TestPingClient.java
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.ping;
-
-import org.apache.log4j.Logger;
-import org.apache.log4j.Level;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQTopic;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.jms.Session;
-
-import javax.jms.*;
-import java.net.InetAddress;
-
-public class TestPingClient
-{
- private static final Logger _logger = Logger.getLogger(TestPingClient.class);
-
- private static class TestPingMessageListener implements MessageListener
- {
- public TestPingMessageListener()
- {
- }
-
- long _lastTimestamp = 0L;
- long _lastTimestampString = 0L;
-
- public void onMessage(javax.jms.Message message)
- {
- if (_logger.isInfoEnabled())
- {
- long timestamp = 0L;
- long timestampString = 0L;
-
- try
- {
- timestamp = message.getLongProperty("timestamp");
- timestampString = Long.parseLong(message.getStringProperty("timestampString"));
-
- if (timestampString != timestamp)
- {
- _logger.info("Timetamps differ!:\n" +
- "timestamp:" + timestamp + "\n" +
- "timestampString:" + timestampString);
- }
-
- }
- catch (JMSException jmse)
- {
- }
-
- long diff = timestamp - _lastTimestamp;
- _lastTimestamp = timestamp;
-
- long stringDiff = timestampString - _lastTimestampString;
-
- _lastTimestampString = timestampString;
-
- _logger.info("Ping: T:" + diff + "ms, TS:" + stringDiff);
-
- // _logger.info(_name + " got message '" + message + "\n");
- }
- }
- }
-
- public static void main(String[] args)
- {
- _logger.setLevel(Level.INFO);
-
- _logger.info("Starting...");
-
- if (args.length < 4)
- {
- System.out.println("Usage: brokerdetails username password virtual-path [selector] ");
- System.exit(1);
- }
- try
- {
- InetAddress address = InetAddress.getLocalHost();
- AMQConnection con1 = new AMQConnection(args[0], args[1], args[2],
- address.getHostName(), args[3]);
-
- final org.apache.qpid.jms.Session session1 = (org.apache.qpid.jms.Session)
- con1.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
-
- String selector = null;
-
- if (args.length == 5)
- {
- selector = args[4];
- }
-
- _logger.info("Message selector is <" + selector + ">...");
-
- Queue q = new AMQQueue("ping");
-
- MessageConsumer consumer1 = session1.createConsumer(q,
- 1, false, false, selector);
-
- consumer1.setMessageListener(new TestPingMessageListener());
- con1.start();
- }
- catch (Throwable t)
- {
- System.err.println("Fatal error: " + t);
- t.printStackTrace();
- }
-
- System.out.println("Waiting...");
- }
-}
-
diff --git a/java/client/src/old_test/java/org/apache/qpid/ping/TestPingProducer.java b/java/client/src/old_test/java/org/apache/qpid/ping/TestPingProducer.java
deleted file mode 100644
index 458dca0d56..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/ping/TestPingProducer.java
+++ /dev/null
@@ -1,213 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.ping;
-
-import org.apache.log4j.Logger;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.url.URLSyntaxException;
-import org.apache.qpid.client.AMQNoConsumersException;
-import org.apache.qpid.client.BasicMessageProducer;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.jms.MessageProducer;
-import org.apache.qpid.jms.Session;
-
-import javax.jms.*;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-
-/**
- * A client that behaves as follows:
- * <ul><li>Connects to a queue, whose name is specified as a cmd-line argument</li>
- * <li>Creates a temporary queue</li>
- * <li>Creates messages containing a property that is the name of the temporary queue</li>
- * <li>Fires off a message on the original queue and waits for a response on the temporary queue</li>
- * </ul>
- */
-public class TestPingProducer implements ExceptionListener
-{
- private static final Logger _log = Logger.getLogger(TestPingProducer.class);
-
- private AMQConnection _connection;
-
- private Session _session;
-
- private boolean _publish;
-
- private long SLEEP_TIME = 250L;
-
- private class CallbackHandler implements MessageListener
- {
-
- private int _actualMessageCount;
-
-
- public void onMessage(Message m)
- {
- if (_log.isDebugEnabled())
- {
- _log.debug("Message received: " + m);
- }
- _actualMessageCount++;
- if (_actualMessageCount % 1000 == 0)
- {
- _log.info("Received message count: " + _actualMessageCount);
- }
- }
- }
-
- public TestPingProducer(boolean TRANSACTED, String brokerDetails, String clientID,
- String virtualpath) throws AMQException, URLSyntaxException
- {
- try
- {
- createConnection(brokerDetails, clientID, virtualpath);
-
- if (TRANSACTED)
- {
- _session = (Session) _connection.createSession(true, Session.SESSION_TRANSACTED);
- }
- else
- {
- _session = (Session) _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- }
-
- AMQQueue destination = new AMQQueue("ping");
- MessageProducer producer = (MessageProducer) _session.createProducer(destination);
-
- _connection.setExceptionListener(this);
-
- _connection.start();
-
- int messageNumber = 0;
-
- while (_publish)
- {
-/*
- TextMessage msg = _session.createTextMessage(
- "Presented to in conjunction with Mahnah Mahnah and the Snowths: " + ++messageNumber);
-*/
- ObjectMessage msg = _session.createObjectMessage();
-
- msg.setStringProperty("timestampString", Long.toString(System.currentTimeMillis()));
- msg.setLongProperty("timestamp", System.currentTimeMillis());
-
- ((BasicMessageProducer) producer).send(msg, DeliveryMode.NON_PERSISTENT, true);
-
-
- if (TRANSACTED)
- {
- try{
- _session.commit();
- _log.info("Message Sent.");// +"\n"+ msg);
- }catch (JMSException e)
- {
- try
- {
- _session.rollback();
- }
- catch (JMSException jsme)
- {
- _log.info(jsme);
- }
-
-
- if (e.getLinkedException() instanceof AMQNoConsumersException)
- {
- _log.info("No Consumers never mind.");
-
- continue;
- }
- }
- }
-
-
- if (SLEEP_TIME > 0)
- {
- try
- {
- Thread.sleep(SLEEP_TIME);
- }
- catch (InterruptedException ie)
- {
- //do nothing
- }
- }
-
-
- }
-
- }
- catch (JMSException e)
- {
- _publish = false;
- e.printStackTrace();
- }
- }
-
- private void createConnection(String brokerDetails, String clientID, String virtualpath) throws AMQException, URLSyntaxException
- {
- _publish = true;
- _connection = new AMQConnection(brokerDetails, "guest", "guest",
- clientID, virtualpath);
- }
-
- /**
- * @param args argument 1 if present specifies the name of the temporary queue to create. Leaving it blank
- * means the server will allocate a name.
- */
- public static void main(String[] args) throws URLSyntaxException
- {
- if (args.length == 0)
- {
- System.err.println("Usage: TestPingPublisher <brokerDetails> <virtual path> [transacted]");
- System.exit(0);
- }
- try
- {
- InetAddress address = InetAddress.getLocalHost();
- String clientID = address.getHostName() + System.currentTimeMillis();
- new TestPingProducer(args.length == 3, args[0], clientID, args[1]);
- }
- catch (UnknownHostException e)
- {
- e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
- }
- catch (AMQException e)
- {
- System.err.println("Error in client: " + e);
- e.printStackTrace();
- }
-
- //System.exit(0);
- }
-
- /**
- * @see javax.jms.ExceptionListener#onException(javax.jms.JMSException)
- */
- public void onException(JMSException e)
- {
- System.err.println(e.getMessage());
-
- _publish = false;
- e.printStackTrace(System.err);
- }
-}
diff --git a/java/client/src/old_test/java/org/apache/qpid/ping/TestPingPublisher.java b/java/client/src/old_test/java/org/apache/qpid/ping/TestPingPublisher.java
deleted file mode 100644
index c7742be042..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/ping/TestPingPublisher.java
+++ /dev/null
@@ -1,180 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.ping;
-
-import org.apache.log4j.Logger;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.url.URLSyntaxException;
-import org.apache.qpid.client.AMQTopic;
-import org.apache.qpid.client.BasicMessageProducer;
-import org.apache.qpid.jms.MessageProducer;
-import org.apache.qpid.jms.Session;
-
-import javax.jms.*;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-
-/**
- * A client that behaves as follows:
- * <ul><li>Connects to a queue, whose name is specified as a cmd-line argument</li>
- * <li>Creates a temporary queue</li>
- * <li>Creates messages containing a property that is the name of the temporary queue</li>
- * <li>Fires off a message on the original queue and waits for a response on the temporary queue</li>
- * </ul>
- */
-public class TestPingPublisher implements ExceptionListener
-{
- private static final Logger _log = Logger.getLogger(TestPingPublisher.class);
-
- private AMQConnection _connection;
-
- private Session _session;
-
- private boolean _publish;
-
- private long SLEEP_TIME = 0L;
-
- private class CallbackHandler implements MessageListener
- {
-
- private int _actualMessageCount;
-
-
- public void onMessage(Message m)
- {
- if (_log.isDebugEnabled())
- {
- _log.debug("Message received: " + m);
- }
- _actualMessageCount++;
- if (_actualMessageCount % 1000 == 0)
- {
- _log.info("Received message count: " + _actualMessageCount);
- }
- }
- }
-
- public TestPingPublisher(String brokerDetails, String clientID, String virtualpath) throws AMQException, URLSyntaxException
- {
- try
- {
- createConnection(brokerDetails, clientID, virtualpath);
-
- _session = (Session) _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- //AMQQueue destination = new AMQQueue("ping");
- AMQTopic destination = new AMQTopic("ping");
- MessageProducer producer = (MessageProducer) _session.createProducer(destination);
-
- _connection.setExceptionListener(this);
-
- _connection.start();
-
- int messageNumber = 0;
-
- while (_publish)
- {
-/*
- TextMessage msg = _session.createTextMessage(
- "Presented to in conjunction with Mahnah Mahnah and the Snowths: " + ++messageNumber);
-*/
- ObjectMessage msg = _session.createObjectMessage();
-
- Long time = System.nanoTime();
- msg.setStringProperty("timestampString", Long.toString(time));
- msg.setLongProperty("timestamp", time);
-
- ((BasicMessageProducer) producer).send(msg, DeliveryMode.PERSISTENT, true);
-
- _log.info("Message Sent:\n" + msg);
-
- if (SLEEP_TIME > 0)
- {
- try
- {
- Thread.sleep(SLEEP_TIME);
- }
- catch (InterruptedException ie)
- {
- //do nothing
- }
- }
-
-
- }
-
- }
- catch (JMSException e)
- {
- e.printStackTrace();
- }
- }
-
- private void createConnection(String brokerDetails, String clientID, String virtualpath) throws AMQException, URLSyntaxException
- {
- _publish = true;
- _connection = new AMQConnection(brokerDetails, "guest", "guest",
- clientID, virtualpath);
-
- }
-
- /**
- * @param args argument 1 if present specifies the name of the temporary queue to create. Leaving it blank
- * means the server will allocate a name.
- */
- public static void main(String[] args) throws URLSyntaxException
- {
- if (args.length == 0)
- {
- System.err.println("Usage: TestPingPublisher <brokerDetails> <virtual path>");
- System.exit(0);
- }
- try
- {
- InetAddress address = InetAddress.getLocalHost();
- String clientID = address.getHostName() + System.currentTimeMillis();
- new TestPingPublisher(args[0], clientID, args[1]);
- }
- catch (UnknownHostException e)
- {
- e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
- }
- catch (AMQException e)
- {
- System.err.println("Error in client: " + e);
- e.printStackTrace();
- }
-
- //System.exit(0);
- }
-
- /**
- * @see javax.jms.ExceptionListener#onException(javax.jms.JMSException)
- */
- public void onException(JMSException e)
- {
- System.err.println(e.getMessage());
-
- _publish = false;
- e.printStackTrace(System.err);
- }
-}
diff --git a/java/client/src/old_test/java/org/apache/qpid/ping/TestPingSubscriber.java b/java/client/src/old_test/java/org/apache/qpid/ping/TestPingSubscriber.java
deleted file mode 100644
index 8e8c3f2e6e..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/ping/TestPingSubscriber.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.ping;
-
-import org.apache.log4j.Logger;
-import org.apache.log4j.Level;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQTopic;
-import org.apache.qpid.jms.Session;
-
-import javax.jms.MessageConsumer;
-import javax.jms.MessageListener;
-import javax.jms.Topic;
-import javax.jms.JMSException;
-import java.net.InetAddress;
-
-public class TestPingSubscriber
-{
- private static final Logger _logger = Logger.getLogger(TestPingClient.class);
-
- private static class TestPingMessageListener implements MessageListener
- {
- public TestPingMessageListener()
- {
- }
-
- long _lastTimestamp = 0L;
- long _lastTimestampString = 0L;
-
- public void onMessage(javax.jms.Message message)
- {
- Long time = System.nanoTime();
-
- if (_logger.isInfoEnabled())
- {
- long timestamp = 0L;
- long timestampString = 0L;
-
- try
- {
- timestamp = message.getLongProperty("timestamp");
- timestampString = Long.parseLong(message.getStringProperty("timestampString"));
-
- if (timestampString != timestamp)
- {
- _logger.info("Timetamps differ!:\n" +
- "timestamp:" + timestamp + "\n" +
- "timestampString:" + timestampString);
- }
-
- }
- catch (JMSException jmse)
- {
- }
-
- long diff = time - timestamp;
-
- long stringDiff = time - timestampString;
-
- _logger.info("Ping: TS:" + stringDiff/1000+"us");
-
- // _logger.info(_name + " got message '" + message + "\n");
- }
- }
- }
-
- public static void main(String[] args)
- {
- _logger.setLevel(Level.INFO);
-
- _logger.info("Starting...");
-
- if (args.length < 4)
- {
- System.out.println("Usage: brokerdetails username password virtual-path [selector] ");
- System.exit(1);
- }
- try
- {
- InetAddress address = InetAddress.getLocalHost();
- AMQConnection con1 = new AMQConnection(args[0], args[1], args[2],
- address.getHostName(), args[3]);
-
- final org.apache.qpid.jms.Session session1 = (org.apache.qpid.jms.Session)
- con1.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
-
- String selector = null;
-
- if (args.length == 5)
- {
- selector = args[4];
- }
-
- _logger.info("Message selector is <" + selector + ">...");
-
- Topic t = new AMQTopic("ping");
-
- MessageConsumer consumer1 = session1.createConsumer(t,
- 1, false, false, selector);
-
- consumer1.setMessageListener(new TestPingMessageListener());
- con1.start();
- }
- catch (Throwable t)
- {
- System.err.println("Fatal error: " + t);
- t.printStackTrace();
- }
-
- System.out.println("Waiting...");
- }
-}
-
diff --git a/java/client/src/old_test/java/org/apache/qpid/requestreply1/ServiceProvidingClient.java b/java/client/src/old_test/java/org/apache/qpid/requestreply1/ServiceProvidingClient.java
deleted file mode 100644
index 7cbec7c85c..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/requestreply1/ServiceProvidingClient.java
+++ /dev/null
@@ -1,201 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.requestreply1;
-
-import org.apache.log4j.Logger;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.jms.Session;
-import org.apache.qpid.jms.ConnectionListener;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.url.URLSyntaxException;
-
-import javax.jms.*;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-
-public class ServiceProvidingClient
-{
- private static final Logger _logger = Logger.getLogger(ServiceProvidingClient.class);
-
- private MessageProducer _destinationProducer;
-
- private Destination _responseDest;
-
- private AMQConnection _connection;
-
- public ServiceProvidingClient(String brokerDetails, String username, String password,
- String clientName, String virtualPath, String serviceName)
- throws AMQException, JMSException, URLSyntaxException
- {
- _connection = new AMQConnection(brokerDetails, username, password,
- clientName, virtualPath);
- _connection.setConnectionListener(new ConnectionListener()
- {
-
- public void bytesSent(long count)
- {
- }
-
- public void bytesReceived(long count)
- {
- }
-
- public boolean preFailover(boolean redirect)
- {
- return true;
- }
-
- public boolean preResubscribe()
- {
- return true;
- }
-
- public void failoverComplete()
- {
- _logger.info("App got failover complete callback");
- }
- });
- final Session session = (Session) _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- _logger.info("Service (queue) name is '" + serviceName + "'...");
-
- AMQQueue destination = new AMQQueue(serviceName);
-
- MessageConsumer consumer = session.createConsumer(destination,
- 100, true, false, null);
-
- consumer.setMessageListener(new MessageListener()
- {
- private int _messageCount;
-
- public void onMessage(Message message)
- {
- //_logger.info("Got message '" + message + "'");
-
- TextMessage tm = (TextMessage) message;
-
- try
- {
- Destination responseDest = tm.getJMSReplyTo();
- if (responseDest == null)
- {
- _logger.info("Producer not created because the response destination is null.");
- return;
- }
-
- if (!responseDest.equals(_responseDest))
- {
- _responseDest = responseDest;
-
- _logger.info("About to create a producer");
- _destinationProducer = session.createProducer(responseDest);
- _destinationProducer.setDisableMessageTimestamp(true);
- _destinationProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
- _logger.info("After create a producer");
- }
- }
- catch (JMSException e)
- {
- _logger.error("Error creating destination");
- }
- _messageCount++;
- if (_messageCount % 1000 == 0)
- {
- _logger.info("Received message total: " + _messageCount);
- _logger.info("Sending response to '" + _responseDest + "'");
- }
-
- try
- {
- String payload = "This is a response: sing together: 'Mahnah mahnah...'" + tm.getText();
- TextMessage msg = session.createTextMessage(payload);
- if (tm.propertyExists("timeSent"))
- {
- _logger.info("timeSent property set on message");
- _logger.info("timeSent value is: " + tm.getLongProperty("timeSent"));
- msg.setStringProperty("timeSent", tm.getStringProperty("timeSent"));
- }
- _destinationProducer.send(msg);
- if (_messageCount % 1000 == 0)
- {
- _logger.info("Sent response to '" + _responseDest + "'");
- }
- }
- catch (JMSException e)
- {
- _logger.error("Error sending message: " + e, e);
- }
- }
- });
- }
-
- public void run() throws JMSException
- {
- _connection.start();
- _logger.info("Waiting...");
- }
-
- public static void main(String[] args)
- {
- _logger.info("Starting...");
-
- if (args.length < 5)
- {
- System.out.println("Usage: brokerDetails username password virtual-path serviceQueue [selector]");
- System.exit(1);
- }
- String clientId = null;
- try
- {
- InetAddress address = InetAddress.getLocalHost();
- clientId = address.getHostName() + System.currentTimeMillis();
- }
- catch (UnknownHostException e)
- {
- _logger.error("Error: " + e, e);
- }
-
- try
- {
- ServiceProvidingClient client = new ServiceProvidingClient(args[0], args[1], args[2],
- clientId, args[3], args[4]);
- client.run();
- }
- catch (JMSException e)
- {
- _logger.error("Error: " + e, e);
- }
- catch (AMQException e)
- {
- _logger.error("Error: " + e, e);
- }
- catch (URLSyntaxException e)
- {
- _logger.error("Error: " + e, e);
- }
-
-
-
- }
-
-}
-
diff --git a/java/client/src/old_test/java/org/apache/qpid/requestreply1/ServiceRequestingClient.java b/java/client/src/old_test/java/org/apache/qpid/requestreply1/ServiceRequestingClient.java
deleted file mode 100644
index 74becfd9bb..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/requestreply1/ServiceRequestingClient.java
+++ /dev/null
@@ -1,303 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.requestreply1;
-
-import org.apache.log4j.Logger;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.url.URLSyntaxException;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQDestination;
-import org.apache.qpid.jms.MessageConsumer;
-import org.apache.qpid.jms.MessageProducer;
-import org.apache.qpid.jms.Session;
-
-import javax.jms.*;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-
-/**
- * A client that behaves as follows:
- * <ul><li>Connects to a queue, whose name is specified as a cmd-line argument</li>
- * <li>Creates a temporary queue</li>
- * <li>Creates messages containing a property that is the name of the temporary queue</li>
- * <li>Fires off a message on the original queue and waits for a response on the temporary queue</li>
- * </ul>
- *
- */
-public class ServiceRequestingClient implements ExceptionListener
-{
- private static final Logger _log = Logger.getLogger(ServiceRequestingClient.class);
-
- private static final String MESSAGE_DATA_BYTES = "jfd ghljgl hjvhlj cvhvjf ldhfsj lhfdsjf hldsjfk hdslkfj hsdflk ";
-
- private String MESSAGE_DATA;
-
- private AMQConnection _connection;
-
- private Session _session;
-
- private long _averageLatency;
-
- private int _messageCount;
-
- private volatile boolean _completed;
-
- private AMQDestination _tempDestination;
-
- private MessageProducer _producer;
-
- private Object _waiter;
-
- private static String createMessagePayload(int size)
- {
- _log.info("Message size set to " + size + " bytes");
- StringBuffer buf = new StringBuffer(size);
- int count = 0;
- while (count < size + MESSAGE_DATA_BYTES.length())
- {
- buf.append(MESSAGE_DATA_BYTES);
- count += MESSAGE_DATA_BYTES.length();
- }
- if (count < size)
- {
- buf.append(MESSAGE_DATA_BYTES, 0, size - count);
- }
-
- return buf.toString();
- }
-
- private class CallbackHandler implements MessageListener
- {
- private int _expectedMessageCount;
-
- private int _actualMessageCount;
-
- private long _startTime;
-
- public CallbackHandler(int expectedMessageCount, long startTime)
- {
- _expectedMessageCount = expectedMessageCount;
- _startTime = startTime;
- }
-
- public void onMessage(Message m)
- {
- if (_log.isDebugEnabled())
- {
- _log.debug("Message received: " + m);
- }
- try
- {
- m.getPropertyNames();
- if (m.propertyExists("timeSent"))
- {
- long timeSent = Long.parseLong(m.getStringProperty("timeSent"));
- long now = System.currentTimeMillis();
- if (_averageLatency == 0)
- {
- _averageLatency = now - timeSent;
- _log.info("Latency " + _averageLatency);
- }
- else
- {
- _log.info("Individual latency: " + (now - timeSent));
- _averageLatency = (_averageLatency + (now - timeSent)) / 2;
- _log.info("Average latency now: " + _averageLatency);
- }
- }
- }
- catch (JMSException e)
- {
- _log.error("Error getting latency data: " + e, e);
- }
- _actualMessageCount++;
- if (_actualMessageCount % 1000 == 0)
- {
- _log.info("Received message count: " + _actualMessageCount);
- }
-
- if (_actualMessageCount == _expectedMessageCount)
- {
- _completed = true;
- notifyWaiter();
- long timeTaken = System.currentTimeMillis() - _startTime;
- _log.info("Total time taken to receive " + _expectedMessageCount + " messages was " +
- timeTaken + "ms, equivalent to " +
- (_expectedMessageCount / (timeTaken / 1000.0)) + " messages per second");
-
- try
- {
- _connection.close();
- _log.info("Connection closed");
- }
- catch (JMSException e)
- {
- _log.error("Error closing connection");
- }
- }
- }
- }
-
- private void notifyWaiter()
- {
- if (_waiter != null)
- {
- synchronized (_waiter)
- {
- _waiter.notify();
- }
- }
- }
- public ServiceRequestingClient(String brokerHosts, String clientID, String username, String password,
- String vpath, String commandQueueName,
- final int messageCount, final int messageDataLength) throws AMQException, URLSyntaxException
- {
- _messageCount = messageCount;
- MESSAGE_DATA = createMessagePayload(messageDataLength);
- try
- {
- createConnection(brokerHosts, clientID, username, password, vpath);
- _session = (Session) _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
-
- _connection.setExceptionListener(this);
-
-
- AMQQueue destination = new AMQQueue(commandQueueName);
- _producer = (MessageProducer) _session.createProducer(destination);
- _producer.setDisableMessageTimestamp(true);
- _producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
-
- _tempDestination = new AMQQueue("TempResponse" +
- Long.toString(System.currentTimeMillis()), true);
- MessageConsumer messageConsumer = (MessageConsumer) _session.createConsumer(_tempDestination, 100, true,
- true, null);
-
- //Send first message, then wait a bit to allow the provider to get initialised
- TextMessage first = _session.createTextMessage(MESSAGE_DATA);
- first.setJMSReplyTo(_tempDestination);
- _producer.send(first);
- try
- {
- Thread.sleep(1000);
- }
- catch (InterruptedException ignore)
- {
- }
-
- //now start the clock and the test...
- final long startTime = System.currentTimeMillis();
-
- messageConsumer.setMessageListener(new CallbackHandler(messageCount, startTime));
- }
- catch (JMSException e)
- {
- e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
- }
- }
-
- /**
- * Run the test and notify an object upon receipt of all responses.
- * @param waiter the object that will be notified
- * @throws JMSException
- */
- public void run(Object waiter) throws JMSException
- {
- _waiter = waiter;
- _connection.start();
- for (int i = 1; i < _messageCount; i++)
- {
- TextMessage msg = _session.createTextMessage(MESSAGE_DATA + i);
- msg.setJMSReplyTo(_tempDestination);
- if (i % 1000 == 0)
- {
- long timeNow = System.currentTimeMillis();
- msg.setStringProperty("timeSent", String.valueOf(timeNow));
- }
- _producer.send(msg);
- }
- _log.info("Finished sending " + _messageCount + " messages");
- }
-
- public boolean isCompleted()
- {
- return _completed;
- }
-
- private void createConnection(String brokerHosts, String clientID, String username, String password,
- String vpath) throws AMQException, URLSyntaxException
- {
- _connection = new AMQConnection(brokerHosts, username, password,
- clientID, vpath);
- }
-
- /**
- * @param args argument 1 if present specifies the name of the temporary queue to create. Leaving it blank
- * means the server will allocate a name.
- */
- public static void main(String[] args)
- {
- if (args.length < 6)
- {
- System.err.println(
- "Usage: ServiceRequestingClient <brokerDetails - semicolon separated host:port list> <username> <password> <vpath> <command queue name> <number of messages> <message size>");
- }
- try
- {
- int messageDataLength = args.length > 6 ? Integer.parseInt(args[6]) : 4096;
-
- InetAddress address = InetAddress.getLocalHost();
- String clientID = address.getHostName() + System.currentTimeMillis();
- ServiceRequestingClient client = new ServiceRequestingClient(args[0], clientID, args[1], args[2], args[3],
- args[4], Integer.parseInt(args[5]),
- messageDataLength);
- Object waiter = new Object();
- client.run(waiter);
- synchronized (waiter)
- {
- while (!client.isCompleted())
- {
- waiter.wait();
- }
- }
-
- }
- catch (UnknownHostException e)
- {
- e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
- }
- catch (Exception e)
- {
- System.err.println("Error in client: " + e);
- e.printStackTrace();
- }
- }
-
- /**
- * @see javax.jms.ExceptionListener#onException(javax.jms.JMSException)
- */
- public void onException(JMSException e)
- {
- System.err.println(e.getMessage());
- e.printStackTrace(System.err);
- }
-}
diff --git a/java/client/src/old_test/java/org/apache/qpid/requestreply1/VmRequestReply.java b/java/client/src/old_test/java/org/apache/qpid/requestreply1/VmRequestReply.java
deleted file mode 100644
index 56d1ce9b6d..0000000000
--- a/java/client/src/old_test/java/org/apache/qpid/requestreply1/VmRequestReply.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.requestreply1;
-
-import org.apache.qpid.client.vmbroker.AMQVMBrokerCreationException;
-import org.apache.qpid.client.transport.TransportConnection;
-import org.apache.qpid.test.VMBrokerSetup;
-import org.apache.log4j.Logger;
-
-import junit.framework.TestCase;
-
-public class VmRequestReply extends TestCase
-{
- private static final Logger _logger = Logger.getLogger(VmRequestReply.class);
-
- public void testSimpleClient() throws Exception
- {
- ServiceProvidingClient serviceProvider = new ServiceProvidingClient("vm://:1", "guest", "guest",
- "serviceProvidingClient", "/test",
- "serviceQ");
-
- ServiceRequestingClient serviceRequester = new ServiceRequestingClient("vm://:1", "myClient", "guest", "guest",
- "/test", "serviceQ", 5000, 512);
-
- serviceProvider.run();
- Object waiter = new Object();
- serviceRequester.run(waiter);
- synchronized (waiter)
- {
- while (!serviceRequester.isCompleted())
- {
- waiter.wait();
- }
- }
- }
-
- public static void main(String[] args)
- {
- VmRequestReply rr = new VmRequestReply();
- try
- {
- rr.testSimpleClient();
- }
- catch (Exception e)
- {
- _logger.error("Error: " + e, e);
- }
- }
-
- public static junit.framework.Test suite()
- {
- return new VMBrokerSetup(new junit.framework.TestSuite(VmRequestReply.class));
- }
-}
diff --git a/java/client/src/old_test/java/org/apache/qpid/test/unit/client/connection/TestManyConnections.java b/java/client/src/old_test/java/org/apache/qpid/test/unit/client/connection/TestManyConnections.java
index d89bc4a771..f59b36166a 100644
--- a/java/client/src/old_test/java/org/apache/qpid/test/unit/client/connection/TestManyConnections.java
+++ b/java/client/src/old_test/java/org/apache/qpid/test/unit/client/connection/TestManyConnections.java
@@ -46,7 +46,7 @@ public class TestManyConnections extends TestCase
long startTime = System.currentTimeMillis();
for (int i = 0; i < count; i++)
{
- createConnection(i, "vm://:1", "myClient" + i, "guest", "guest", "/test");
+ createConnection(i, "vm://:1", "myClient" + i, "guest", "guest", "test");
}
long endTime = System.currentTimeMillis();
_log.info("Time to create " + count + " connections: " + (endTime - startTime) +
diff --git a/java/client/src/old_test/java/org/apache/qpid/test/unit/jndi/referenceabletest/JNDIReferenceableTest.java b/java/client/src/old_test/java/org/apache/qpid/test/unit/jndi/referenceabletest/JNDIReferenceableTest.java
index 4731caca98..9fc186f19a 100644
--- a/java/client/src/old_test/java/org/apache/qpid/test/unit/jndi/referenceabletest/JNDIReferenceableTest.java
+++ b/java/client/src/old_test/java/org/apache/qpid/test/unit/jndi/referenceabletest/JNDIReferenceableTest.java
@@ -7,9 +7,9 @@
* 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
@@ -20,15 +20,12 @@
*/
package org.apache.qpid.test.unit.jndi.referenceabletest;
-import org.apache.qpid.client.transport.TransportConnection;
-import org.apache.qpid.client.vmbroker.AMQVMBrokerCreationException;
-import org.apache.qpid.test.VMBrokerSetup;
+import junit.framework.TestCase;
+//import org.apache.qpid.testutil.VMBrokerSetup;
import javax.naming.NameAlreadyBoundException;
import javax.naming.NoInitialContextException;
-import junit.framework.TestCase;
-
/**
* Usage: To run these you need to have the sun JNDI SPI for the FileSystem.
* This can be downloaded from sun here:
@@ -41,7 +38,7 @@ import junit.framework.TestCase;
*/
public class JNDIReferenceableTest extends TestCase
{
- // FIXME FSContext has been removed from repository. This needs redone with the PropertiesFileInitialContextFactory. QPID-84
+/* // FIXME FSContext has been removed from repository. This needs redone with the PropertiesFileInitialContextFactory. QPID-84
public void testReferenceable()
{
Bind b = null;
@@ -101,4 +98,5 @@ public class JNDIReferenceableTest extends TestCase
{
return new VMBrokerSetup(new junit.framework.TestSuite(JNDIReferenceableTest.class));
}
+ */
}
diff --git a/java/client/src/old_test/java/org/apache/qpid/weblogic/ServiceRequestingClient.java b/java/client/src/old_test/java/org/apache/qpid/weblogic/ServiceRequestingClient.java
index a1e15258c3..2f64a1dde5 100644
--- a/java/client/src/old_test/java/org/apache/qpid/weblogic/ServiceRequestingClient.java
+++ b/java/client/src/old_test/java/org/apache/qpid/weblogic/ServiceRequestingClient.java
@@ -7,9 +7,9 @@
* 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
@@ -20,20 +20,13 @@
*/
package org.apache.qpid.weblogic;
-import org.apache.qpid.jms.*;
import org.apache.log4j.Logger;
-import javax.naming.NamingException;
-import javax.naming.InitialContext;
-import javax.naming.Context;
import javax.jms.*;
-import javax.jms.MessageConsumer;
-import javax.jms.Session;
+import javax.naming.Context;
+import javax.naming.InitialContext;
+import javax.naming.NamingException;
import java.util.Hashtable;
-import java.io.File;
-import java.io.FilenameFilter;
-import java.io.Reader;
-import java.io.FileReader;
/**
* Created by IntelliJ IDEA.
diff --git a/java/client/src/test/java/org/apache/qpid/client/MessageListenerMultiConsumerTest.java b/java/client/src/test/java/org/apache/qpid/client/MessageListenerMultiConsumerTest.java
new file mode 100644
index 0000000000..6b03dd32e8
--- /dev/null
+++ b/java/client/src/test/java/org/apache/qpid/client/MessageListenerMultiConsumerTest.java
@@ -0,0 +1,213 @@
+/*
+ * 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.client;
+
+import junit.framework.TestCase;
+import org.apache.log4j.Logger;
+import org.apache.qpid.client.transport.TransportConnection;
+import org.apache.qpid.jndi.PropertiesFileInitialContextFactory;
+
+import javax.jms.Connection;
+import javax.jms.Session;
+import javax.jms.MessageProducer;
+import javax.jms.Queue;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageListener;
+import javax.jms.Message;
+import javax.jms.ConnectionFactory;
+import javax.naming.Context;
+import javax.naming.spi.InitialContextFactory;
+import java.util.Hashtable;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * QPID-293 Setting MessageListener after connection has started can cause messages to be "lost" on a internal delivery queue
+ * <p/>
+ * The message delivery process:
+ * Mina puts a message on _queue in AMQSession and the dispatcher thread take()s
+ * from here and dispatches to the _consumers. If the _consumer1 doesn't have a message listener set at connection start
+ * then messages are stored on _synchronousQueue (which needs to be > 1 to pass JMS TCK as multiple consumers on a
+ * session can run in any order and a synchronous put/poll will block the dispatcher).
+ * <p/>
+ * When setting the message listener later the _synchronousQueue is just poll()'ed and the first message delivered
+ * the remaining messages will be left on the queue and lost, subsequent messages on the session will arrive first.
+ */
+public class MessageListenerMultiConsumerTest extends TestCase
+{
+ private static final Logger _logger = Logger.getLogger(MessageListenerMultiConsumerTest.class);
+
+ Context _context;
+
+ private static final int MSG_COUNT = 6;
+ private int receivedCount1 = 0;
+ private int receivedCount2 = 0;
+ private Connection _clientConnection;
+ private MessageConsumer _consumer1;
+ private MessageConsumer _consumer2;
+
+ private boolean _testAsync;
+ private final CountDownLatch _allMessagesSent = new CountDownLatch(2); //all messages Sent Lock
+
+ protected void setUp() throws Exception
+ {
+ super.setUp();
+ TransportConnection.createVMBroker(1);
+
+ InitialContextFactory factory = new PropertiesFileInitialContextFactory();
+
+ Hashtable<String, String> env = new Hashtable<String, String>();
+
+ env.put("connectionfactory.connection", "amqp://client:client@MLT_ID/test?brokerlist='vm://:1'");
+ env.put("queue.queue", "direct://amq.direct//MessageListenerTest");
+
+ _context = factory.getInitialContext(env);
+
+ Queue queue = (Queue) _context.lookup("queue");
+
+ //Create Client 1
+ _clientConnection = ((ConnectionFactory) _context.lookup("connection")).createConnection();
+
+ _clientConnection.start();
+
+ Session clientSession1 = _clientConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+ _consumer1 = clientSession1.createConsumer(queue);
+
+ //Create Client 2
+ Session clientSession2 = _clientConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+ _consumer2 = clientSession2.createConsumer(queue);
+
+ //Create Producer
+ Connection producerConnection = ((ConnectionFactory) _context.lookup("connection")).createConnection();
+
+ producerConnection.start();
+
+
+ Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+ MessageProducer producer = producerSession.createProducer(queue);
+
+ for (int msg = 0; msg < MSG_COUNT; msg++)
+ {
+ producer.send(producerSession.createTextMessage("Message " + msg));
+ }
+
+ producerConnection.close();
+
+ _testAsync = false;
+ }
+
+ protected void tearDown() throws Exception
+ {
+ //Should have recieved all async messages
+ if (_testAsync)
+ {
+ assertEquals(MSG_COUNT, receivedCount1 + receivedCount2);
+ }
+ _clientConnection.close();
+
+ super.tearDown();
+ TransportConnection.killAllVMBrokers();
+ }
+
+
+ public void testRecieveC1thenC2() throws Exception
+ {
+
+ for (int msg = 0; msg < MSG_COUNT / 2; msg++)
+ {
+
+ assertTrue(_consumer1.receive() != null);
+ }
+
+ for (int msg = 0; msg < MSG_COUNT / 2; msg++)
+ {
+ assertTrue(_consumer2.receive() != null);
+ }
+ }
+
+ public void testRecieveInterleaved() throws Exception
+ {
+
+ for (int msg = 0; msg < MSG_COUNT / 2; msg++)
+ {
+ assertTrue(_consumer1.receive() != null);
+ assertTrue(_consumer2.receive() != null);
+ }
+ }
+
+
+ public void testAsynchronousRecieve() throws Exception
+ {
+ _testAsync = true;
+
+ _consumer1.setMessageListener(new MessageListener()
+ {
+ public void onMessage(Message message)
+ {
+ _logger.info("Client 1 Received Message(" + receivedCount1 + "):" + message);
+
+ receivedCount1++;
+
+ if (receivedCount1 == MSG_COUNT / 2)
+ {
+ _allMessagesSent.countDown();
+ }
+
+ }
+ });
+
+ _consumer2.setMessageListener(new MessageListener()
+ {
+ public void onMessage(Message message)
+ {
+ _logger.info("Client 2 Received Message(" + receivedCount2 + "):" + message);
+
+ receivedCount2++;
+ if (receivedCount2 == MSG_COUNT / 2)
+ {
+ _allMessagesSent.countDown();
+ }
+ }
+ });
+
+
+ _logger.info("Waiting upto 2 seconds for messages");
+
+ try
+ {
+ _allMessagesSent.await(2000, TimeUnit.MILLISECONDS);
+ }
+ catch (InterruptedException e)
+ {
+ //do nothing
+ }
+
+ }
+
+
+ public static junit.framework.Test suite()
+ {
+ return new junit.framework.TestSuite(MessageListenerMultiConsumerTest.class);
+ }
+}
diff --git a/java/client/src/test/java/org/apache/qpid/client/MessageListenerTest.java b/java/client/src/test/java/org/apache/qpid/client/MessageListenerTest.java
new file mode 100644
index 0000000000..0739acfabd
--- /dev/null
+++ b/java/client/src/test/java/org/apache/qpid/client/MessageListenerTest.java
@@ -0,0 +1,164 @@
+/*
+ * 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.client;
+
+import junit.framework.TestCase;
+import org.apache.log4j.Logger;
+import org.apache.qpid.client.transport.TransportConnection;
+import org.apache.qpid.jndi.PropertiesFileInitialContextFactory;
+
+import javax.jms.Connection;
+import javax.jms.Session;
+import javax.jms.MessageProducer;
+import javax.jms.Queue;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageListener;
+import javax.jms.Message;
+import javax.jms.ConnectionFactory;
+import javax.naming.Context;
+import javax.naming.spi.InitialContextFactory;
+import java.util.Hashtable;
+
+/**
+ * QPID-293 Setting MessageListener after connection has started can cause messages to be "lost" on a internal delivery queue
+ * <p/>
+ * The message delivery process:
+ * Mina puts a message on _queue in AMQSession and the dispatcher thread take()s
+ * from here and dispatches to the _consumers. If the _consumer doesn't have a message listener set at connection start
+ * then messages are stored on _synchronousQueue (which needs to be > 1 to pass JMS TCK as multiple consumers on a
+ * session can run in any order and a synchronous put/poll will block the dispatcher).
+ * <p/>
+ * When setting the message listener later the _synchronousQueue is just poll()'ed and the first message delivered
+ * the remaining messages will be left on the queue and lost, subsequent messages on the session will arrive first.
+ */
+public class MessageListenerTest extends TestCase implements MessageListener
+{
+ private static final Logger _logger = Logger.getLogger(MessageListenerTest.class);
+
+ Context _context;
+
+ private static final int MSG_COUNT = 5;
+ private int receivedCount = 0;
+ private MessageConsumer _consumer;
+ private Connection _clientConnection;
+ private boolean _testAsync;
+
+ protected void setUp() throws Exception
+ {
+ super.setUp();
+ TransportConnection.createVMBroker(1);
+
+ InitialContextFactory factory = new PropertiesFileInitialContextFactory();
+
+ Hashtable<String, String> env = new Hashtable<String, String>();
+
+ env.put("connectionfactory.connection", "amqp://client:client@MLT_ID/test?brokerlist='vm://:1'");
+ env.put("queue.queue", "direct://amq.direct//MessageListenerTest");
+
+ _context = factory.getInitialContext(env);
+
+ Queue queue = (Queue) _context.lookup("queue");
+
+ //Create Client
+ _clientConnection = ((ConnectionFactory) _context.lookup("connection")).createConnection();
+
+ _clientConnection.start();
+
+ Session clientSession = _clientConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+
+ _consumer = clientSession.createConsumer(queue);
+
+ //Create Producer
+
+ Connection producerConnection = ((ConnectionFactory) _context.lookup("connection")).createConnection();
+
+ producerConnection.start();
+
+ Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+ MessageProducer producer = producerSession.createProducer(queue);
+
+ for (int msg = 0; msg < MSG_COUNT; msg++)
+ {
+ producer.send(producerSession.createTextMessage("Message " + msg));
+ }
+
+ producerConnection.close();
+
+ _testAsync = false;
+ }
+
+ protected void tearDown() throws Exception
+ {
+ //Should have recieved all async messages
+ if (_testAsync)
+ {
+ assertEquals(MSG_COUNT, receivedCount);
+ }
+ _clientConnection.close();
+
+ super.tearDown();
+ TransportConnection.killAllVMBrokers();
+ }
+
+
+ public void testSynchronousRecieve() throws Exception
+ {
+
+ for (int msg = 0; msg < MSG_COUNT; msg++)
+ {
+ assertTrue(_consumer.receive(2000) != null);
+ }
+ }
+
+ public void testAsynchronousRecieve() throws Exception
+ {
+ _testAsync = true;
+
+ _consumer.setMessageListener(this);
+
+
+ _logger.info("Waiting 3 seconds for messages");
+
+ try
+ {
+ Thread.sleep(2000);
+ }
+ catch (InterruptedException e)
+ {
+ //do nothing
+ }
+
+ }
+
+ public void onMessage(Message message)
+ {
+ _logger.info("Received Message(" + receivedCount + "):" + message);
+
+ receivedCount++;
+ }
+
+ public static junit.framework.Test suite()
+ {
+ return new junit.framework.TestSuite(MessageListenerTest.class);
+ }
+}
diff --git a/java/client/src/test/java/org/apache/qpid/client/message/TestNonQpidTextMessage.java b/java/client/src/test/java/org/apache/qpid/client/message/TestNonQpidTextMessage.java
new file mode 100644
index 0000000000..f7bea1b36a
--- /dev/null
+++ b/java/client/src/test/java/org/apache/qpid/client/message/TestNonQpidTextMessage.java
@@ -0,0 +1,231 @@
+/*
+ *
+ * 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.client.message;
+
+import javax.jms.*;
+import java.util.Enumeration;
+import java.io.Serializable;
+
+public class TestNonQpidTextMessage implements ObjectMessage {
+
+ private JMSObjectMessage _realMessage;
+ private String _contentString;
+
+ /**
+ * Allows us to construct a JMS message which
+ * does not inherit from the Qpid message superclasses
+ * and expand our unit testing of MessageConverter et al
+ */
+ public TestNonQpidTextMessage()
+ {
+ _realMessage = new JMSObjectMessage();
+ }
+
+ public String getJMSMessageID() throws JMSException {
+ return _realMessage.getJMSMessageID();
+ }
+
+ public void setJMSMessageID(String string) throws JMSException {
+ _realMessage.setJMSMessageID(string);
+ }
+
+ public long getJMSTimestamp() throws JMSException {
+ return _realMessage.getJMSTimestamp();
+ }
+
+ public void setJMSTimestamp(long l) throws JMSException {
+ _realMessage.setJMSTimestamp(l);
+ }
+
+ public byte[] getJMSCorrelationIDAsBytes() throws JMSException {
+ return _realMessage.getJMSCorrelationIDAsBytes();
+ }
+
+ public void setJMSCorrelationIDAsBytes(byte[] bytes) throws JMSException {
+ _realMessage.setJMSCorrelationIDAsBytes(bytes);
+ }
+
+ public void setJMSCorrelationID(String string) throws JMSException {
+ _realMessage.setJMSCorrelationID(string);
+ }
+
+ public String getJMSCorrelationID() throws JMSException {
+ return _realMessage.getJMSCorrelationID();
+ }
+
+ public Destination getJMSReplyTo() throws JMSException {
+ return _realMessage.getJMSReplyTo();
+ }
+
+ public void setJMSReplyTo(Destination destination) throws JMSException {
+ _realMessage.setJMSReplyTo(destination);
+ }
+
+ public Destination getJMSDestination() throws JMSException {
+ return _realMessage.getJMSDestination();
+ }
+
+ public void setJMSDestination(Destination destination) throws JMSException {
+ _realMessage.setJMSDestination(destination);
+ }
+
+ public int getJMSDeliveryMode() throws JMSException {
+ return _realMessage.getJMSDeliveryMode();
+ }
+
+ public void setJMSDeliveryMode(int i) throws JMSException {
+ _realMessage.setJMSDeliveryMode(i);
+ }
+
+ public boolean getJMSRedelivered() throws JMSException {
+ return _realMessage.getJMSRedelivered();
+ }
+
+ public void setJMSRedelivered(boolean b) throws JMSException {
+ _realMessage.setJMSRedelivered(b);
+ }
+
+ public String getJMSType() throws JMSException {
+ return _realMessage.getJMSType();
+ }
+
+ public void setJMSType(String string) throws JMSException {
+ _realMessage.setJMSType(string);
+ }
+
+ public long getJMSExpiration() throws JMSException {
+ return _realMessage.getJMSExpiration();
+ }
+
+ public void setJMSExpiration(long l) throws JMSException {
+ _realMessage.setJMSExpiration(l);
+ }
+
+ public int getJMSPriority() throws JMSException {
+ return _realMessage.getJMSPriority();
+ }
+
+ public void setJMSPriority(int i) throws JMSException {
+ _realMessage.setJMSPriority(i);
+ }
+
+ public void clearProperties() throws JMSException {
+ _realMessage.clearProperties();
+ }
+
+ public boolean propertyExists(String string) throws JMSException {
+ return _realMessage.propertyExists(string);
+ }
+
+ public boolean getBooleanProperty(String string) throws JMSException {
+ return _realMessage.getBooleanProperty(string);
+ }
+
+ public byte getByteProperty(String string) throws JMSException {
+ return _realMessage.getByteProperty(string);
+ }
+
+ public short getShortProperty(String string) throws JMSException {
+ return _realMessage.getShortProperty(string);
+ }
+
+ public int getIntProperty(String string) throws JMSException {
+ return _realMessage.getIntProperty(string);
+ }
+
+ public long getLongProperty(String string) throws JMSException {
+ return _realMessage.getLongProperty(string);
+ }
+
+ public float getFloatProperty(String string) throws JMSException {
+ return _realMessage.getFloatProperty(string);
+ }
+
+ public double getDoubleProperty(String string) throws JMSException {
+ return _realMessage.getDoubleProperty(string);
+ }
+
+ public String getStringProperty(String string) throws JMSException {
+ return _realMessage.getStringProperty(string);
+ }
+
+ public Object getObjectProperty(String string) throws JMSException {
+ return _realMessage.getObjectProperty(string);
+ }
+
+ public Enumeration getPropertyNames() throws JMSException {
+ return _realMessage.getPropertyNames();
+ }
+
+ public void setBooleanProperty(String string, boolean b) throws JMSException {
+ _realMessage.setBooleanProperty(string,b);
+ }
+
+ public void setByteProperty(String string, byte b) throws JMSException {
+ _realMessage.setByteProperty(string,b);
+ }
+
+ public void setShortProperty(String string, short i) throws JMSException {
+ _realMessage.setShortProperty(string,i);
+ }
+
+ public void setIntProperty(String string, int i) throws JMSException {
+ _realMessage.setIntProperty(string,i);
+ }
+
+ public void setLongProperty(String string, long l) throws JMSException {
+ _realMessage.setLongProperty(string,l);
+ }
+
+ public void setFloatProperty(String string, float v) throws JMSException {
+ _realMessage.setFloatProperty(string,v);
+ }
+
+ public void setDoubleProperty(String string, double v) throws JMSException {
+ _realMessage.setDoubleProperty(string,v);
+ }
+
+ public void setStringProperty(String string, String string1) throws JMSException {
+ _realMessage.setStringProperty(string,string1);
+ }
+
+ public void setObjectProperty(String string, Object object) throws JMSException {
+ _realMessage.setObjectProperty(string,object);
+ }
+
+ public void acknowledge() throws JMSException {
+ _realMessage.acknowledge();
+ }
+
+ public void clearBody() throws JMSException {
+ _realMessage.clearBody();
+ }
+
+ public void setObject(Serializable serializable) throws JMSException {
+ if (serializable instanceof String)
+ {
+ _contentString = (String)serializable;
+ }
+ }
+
+ public Serializable getObject() throws JMSException {
+ return _contentString; }
+}
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/ack/RecoverTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/ack/RecoverTest.java
index d12ab01bdc..4a8c0145c4 100644
--- a/java/client/src/test/java/org/apache/qpid/test/unit/ack/RecoverTest.java
+++ b/java/client/src/test/java/org/apache/qpid/test/unit/ack/RecoverTest.java
@@ -25,37 +25,46 @@ import org.apache.qpid.client.AMQConnection;
import org.apache.qpid.client.AMQQueue;
import org.apache.qpid.client.AMQSession;
import org.apache.qpid.client.transport.TransportConnection;
+import org.apache.qpid.framing.AMQShortString;
+import org.apache.qpid.exchange.ExchangeDefaults;
import javax.jms.*;
+import java.util.concurrent.atomic.AtomicInteger;
public class RecoverTest extends TestCase
{
private static final Logger _logger = Logger.getLogger(RecoverTest.class);
+ private Exception _error;
+ private AtomicInteger count;
+
protected void setUp() throws Exception
{
super.setUp();
TransportConnection.createVMBroker(1);
+ _error = null;
+ count = new AtomicInteger();
}
protected void tearDown() throws Exception
{
super.tearDown();
TransportConnection.killAllVMBrokers();
+ count = null;
}
public void testRecoverResendsMsgs() throws Exception
{
- Connection con = new AMQConnection("vm://:1", "guest", "guest", "consumer1", "/test");
+ Connection con = new AMQConnection("vm://:1", "guest", "guest", "consumer1", "test");
Session consumerSession = con.createSession(false, Session.CLIENT_ACKNOWLEDGE);
- Queue queue = new AMQQueue("someQ", "someQ", false, true);
+ Queue queue = new AMQQueue(new AMQShortString("someQ"), new AMQShortString("someQ"), false, true);
MessageConsumer consumer = consumerSession.createConsumer(queue);
//force synch to ensure the consumer has resulted in a bound queue
- ((AMQSession) consumerSession).declareExchangeSynch("amq.direct", "direct");
+ ((AMQSession) consumerSession).declareExchangeSynch(ExchangeDefaults.DIRECT_EXCHANGE_NAME, ExchangeDefaults.DIRECT_EXCHANGE_CLASS);
- Connection con2 = new AMQConnection("vm://:1", "guest", "guest", "producer1", "/test");
+ Connection con2 = new AMQConnection("vm://:1", "guest", "guest", "producer1", "test");
Session producerSession = con2.createSession(false, Session.CLIENT_ACKNOWLEDGE);
MessageProducer producer = producerSession.createProducer(queue);
@@ -104,15 +113,15 @@ public class RecoverTest extends TestCase
public void testRecoverResendsMsgsAckOnEarlier() throws Exception
{
- Connection con = new AMQConnection("vm://:1", "guest", "guest", "consumer1", "/test");
+ Connection con = new AMQConnection("vm://:1", "guest", "guest", "consumer1", "test");
Session consumerSession = con.createSession(false, Session.CLIENT_ACKNOWLEDGE);
- Queue queue = new AMQQueue("someQ", "someQ", false, true);
+ Queue queue = new AMQQueue(new AMQShortString("someQ"), new AMQShortString("someQ"), false, true);
MessageConsumer consumer = consumerSession.createConsumer(queue);
//force synch to ensure the consumer has resulted in a bound queue
- ((AMQSession) consumerSession).declareExchangeSynch("amq.direct", "direct");
+ ((AMQSession) consumerSession).declareExchangeSynch(ExchangeDefaults.DIRECT_EXCHANGE_NAME, ExchangeDefaults.DIRECT_EXCHANGE_CLASS);
- Connection con2 = new AMQConnection("vm://:1", "guest", "guest", "producer1", "/test");
+ Connection con2 = new AMQConnection("vm://:1", "guest", "guest", "producer1", "test");
Session producerSession = con2.createSession(false, Session.CLIENT_ACKNOWLEDGE);
MessageProducer producer = producerSession.createProducer(queue);
@@ -168,15 +177,15 @@ public class RecoverTest extends TestCase
public void testAcknowledgePerConsumer() throws Exception
{
- Connection con = new AMQConnection("vm://:1", "guest", "guest", "consumer1", "/test");
+ Connection con = new AMQConnection("vm://:1", "guest", "guest", "consumer1", "test");
Session consumerSession = con.createSession(false, Session.CLIENT_ACKNOWLEDGE);
- Queue queue = new AMQQueue("Q1", "Q1", false, true);
- Queue queue2 = new AMQQueue("Q2", "Q2", false, true);
+ Queue queue = new AMQQueue(new AMQShortString("Q1"), new AMQShortString("Q1"), false, true);
+ Queue queue2 = new AMQQueue(new AMQShortString("Q2"), new AMQShortString("Q2"), false, true);
MessageConsumer consumer = consumerSession.createConsumer(queue);
MessageConsumer consumer2 = consumerSession.createConsumer(queue2);
- Connection con2 = new AMQConnection("vm://:1", "guest", "guest", "producer1", "/test");
+ Connection con2 = new AMQConnection("vm://:1", "guest", "guest", "producer1", "test");
Session producerSession = con2.createSession(false, Session.CLIENT_ACKNOWLEDGE);
MessageProducer producer = producerSession.createProducer(queue);
MessageProducer producer2 = producerSession.createProducer(queue2);
@@ -207,41 +216,96 @@ public class RecoverTest extends TestCase
public void testRecoverInAutoAckListener() throws Exception
{
- Connection con = new AMQConnection("vm://:1", "guest", "guest", "consumer1", "/test");
+ Connection con = new AMQConnection("vm://:1", "guest", "guest", "consumer1", "test");
final Session consumerSession = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
- Queue queue = new AMQQueue("Q1", "Q1", false, true);
+ Queue queue = new AMQQueue(new AMQShortString("Q3"), new AMQShortString("Q3"), false, true);
+ MessageConsumer consumer = consumerSession.createConsumer(queue);
MessageProducer producer = consumerSession.createProducer(queue);
producer.send(consumerSession.createTextMessage("hello"));
- MessageConsumer consumer = consumerSession.createConsumer(queue);
+
+
+ final Object lock = new Object();
+
consumer.setMessageListener(new MessageListener()
{
- private int count = 0;
+
+
public void onMessage(Message message)
{
try
{
- if (count++ == 0)
+ count.incrementAndGet();
+ if (count.get() == 1)
{
- assertFalse(message.getJMSRedelivered());
+ if(message.getJMSRedelivered())
+ {
+ setError(new Exception("Message marked as redilvered on what should be first delivery attempt"));
+ }
consumerSession.recover();
}
- else if (count++ == 1)
+ else if (count.get() == 2)
{
- assertTrue(message.getJMSRedelivered());
+ if(!message.getJMSRedelivered())
+ {
+ setError(new Exception("Message not marked as redilvered on what should be second delivery attempt"));
+ }
}
else
{
- fail("Message delivered too many times!");
+ System.err.println(message);
+ fail("Message delivered too many times!: " + count);
}
}
catch (JMSException e)
{
_logger.error("Error recovering session: " + e, e);
+ setError(e);
+ }
+ synchronized(lock)
+ {
+ lock.notify();
}
}
});
+
+ con.start();
+
+ long waitTime = 300000L;
+ long waitUntilTime = System.currentTimeMillis() + waitTime;
+
+ synchronized(lock)
+ {
+ while((count.get() <= 1) && (waitTime > 0))
+ {
+ lock.wait(waitTime);
+ if(count.get() <= 1)
+ {
+ waitTime = waitUntilTime - System.currentTimeMillis();
+ }
+ }
+ }
+
+ Thread.sleep(1000);
+
+ if(count.get() != 2)
+ {
+ System.err.println("Count != 2 : " + count);
+ }
+ assertTrue(count.get() == 2);
+
+ con.close();
+
+ if(_error != null)
+ {
+ throw _error;
+ }
+ }
+
+ private void setError(Exception e)
+ {
+ _error = e;
}
public static junit.framework.Test suite()
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/basic/BytesMessageTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/basic/BytesMessageTest.java
index 59be38f0dd..cf5b5c76e5 100644
--- a/java/client/src/test/java/org/apache/qpid/test/unit/basic/BytesMessageTest.java
+++ b/java/client/src/test/java/org/apache/qpid/test/unit/basic/BytesMessageTest.java
@@ -48,7 +48,7 @@ public class BytesMessageTest extends TestCase implements MessageListener
protected void setUp() throws Exception
{
super.setUp();
- init(new AMQConnection(_connectionString, "guest", "guest", randomize("Client"), "/test_path"));
+ init(new AMQConnection(_connectionString, "guest", "guest", randomize("Client"), "test"));
}
protected void tearDown() throws Exception
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/basic/FieldTableKeyEnumeratorTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/basic/FieldTableKeyEnumeratorTest.java
index ad180e3a89..fb347053c7 100644
--- a/java/client/src/test/java/org/apache/qpid/test/unit/basic/FieldTableKeyEnumeratorTest.java
+++ b/java/client/src/test/java/org/apache/qpid/test/unit/basic/FieldTableKeyEnumeratorTest.java
@@ -35,16 +35,20 @@ import junit.framework.TestCase;
public class FieldTableKeyEnumeratorTest extends TestCase
{
+ public void testTrue()
+ {
+
+ }
public void testKeyEnumeration()
{
FieldTable result = FieldTableFactory.newFieldTable();
- result.put("one", 1L);
- result.put("two", 2L);
- result.put("three", 3L);
- result.put("four", 4L);
- result.put("five", 5L);
+ result.setObject("one", 1L);
+ result.setObject("two", 2L);
+ result.setObject("three", 3L);
+ result.setObject("four", 4L);
+ result.setObject("five", 5L);
- Iterator iterator = result.keySet().iterator();
+ Iterator iterator = result.keys().iterator();
try
{
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/basic/FieldTableMessageTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/basic/FieldTableMessageTest.java
index f4efd64dbb..d1e90e7bcd 100644
--- a/java/client/src/test/java/org/apache/qpid/test/unit/basic/FieldTableMessageTest.java
+++ b/java/client/src/test/java/org/apache/qpid/test/unit/basic/FieldTableMessageTest.java
@@ -54,7 +54,7 @@ public class FieldTableMessageTest extends TestCase implements MessageListener
protected void setUp() throws Exception
{
super.setUp();
- init(new AMQConnection(_connectionString, "guest", "guest", randomize("Client"), "/test_path"));
+ init(new AMQConnection(_connectionString, "guest", "guest", randomize("Client"), "test"));
}
protected void tearDown() throws Exception
@@ -85,11 +85,11 @@ public class FieldTableMessageTest extends TestCase implements MessageListener
private FieldTable load() throws IOException
{
FieldTable result = FieldTableFactory.newFieldTable();
- result.put("one", 1L);
- result.put("two", 2L);
- result.put("three", 3L);
- result.put("four", 4L);
- result.put("five", 5L);
+ result.setLong("one", 1L);
+ result.setLong("two", 2L);
+ result.setLong("three", 3L);
+ result.setLong("four", 4L);
+ result.setLong("five", 5L);
return result;
}
@@ -133,10 +133,9 @@ public class FieldTableMessageTest extends TestCase implements MessageListener
{
ByteBuffer buffer = ((JMSBytesMessage) m).getData();
FieldTable actual = FieldTableFactory.newFieldTable(buffer, buffer.remaining());
- for (Object o : _expected.keySet())
- {
- String key = (String) o;
- assertEquals("Values for " + key + " did not match", _expected.get(key), actual.get(key));
+ for (String key : _expected.keys())
+ {
+ assertEquals("Values for " + key + " did not match", _expected.getObject(key), actual.getObject(key));
}
}
}
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/basic/MapMessageTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/basic/MapMessageTest.java
index bc2def1c64..29770704c5 100644
--- a/java/client/src/test/java/org/apache/qpid/test/unit/basic/MapMessageTest.java
+++ b/java/client/src/test/java/org/apache/qpid/test/unit/basic/MapMessageTest.java
@@ -56,7 +56,7 @@ public class MapMessageTest extends TestCase implements MessageListener
try
{
TransportConnection.createVMBroker(1);
- init(new AMQConnection(_connectionString, "guest", "guest", randomize("Client"), "/test_path"));
+ init(new AMQConnection(_connectionString, "guest", "guest", randomize("Client"), "test"));
}
catch (Exception e)
{
@@ -144,13 +144,29 @@ public class MapMessageTest extends TestCase implements MessageListener
}
- void waitFor(int count) throws InterruptedException
+ void waitFor(int count) throws Exception
{
+ long waitTime = 30000L;
+ long waitUntilTime = System.currentTimeMillis() + 30000L;
+
+
synchronized(received)
{
- while (received.size() < count)
+ while(received.size() < count && waitTime>0)
+ {
+ if (received.size() < count)
+ {
+ received.wait(waitTime);
+ }
+
+ if (received.size() < count)
+ {
+ waitTime = waitUntilTime - System.currentTimeMillis();
+ }
+ }
+ if (received.size() < count)
{
- received.wait();
+ throw new Exception("Timed-out. Waiting for " + count + " only got " + received.size());
}
}
}
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/basic/MultipleConnectionTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/basic/MultipleConnectionTest.java
index 1e9de221d4..66d82a991e 100644
--- a/java/client/src/test/java/org/apache/qpid/test/unit/basic/MultipleConnectionTest.java
+++ b/java/client/src/test/java/org/apache/qpid/test/unit/basic/MultipleConnectionTest.java
@@ -41,7 +41,7 @@ public class MultipleConnectionTest extends TestCase
Receiver(String broker, AMQDestination dest, int sessions) throws Exception
{
- this(new AMQConnection(broker, "guest", "guest", randomize("Client"), "/test_path"), dest, sessions);
+ this(new AMQConnection(broker, "guest", "guest", randomize("Client"), "test"), dest, sessions);
}
Receiver(AMQConnection connection, AMQDestination dest, int sessions) throws Exception
@@ -72,7 +72,7 @@ public class MultipleConnectionTest extends TestCase
Publisher(String broker, AMQDestination dest) throws Exception
{
- this(new AMQConnection(broker, "guest", "guest", randomize("Client"), "/test_path"), dest);
+ this(new AMQConnection(broker, "guest", "guest", randomize("Client"), "test"), dest);
}
Publisher(AMQConnection connection, AMQDestination dest) throws Exception
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/basic/ObjectMessageTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/basic/ObjectMessageTest.java
index 3f726ae5ab..dc1aadaa6c 100644
--- a/java/client/src/test/java/org/apache/qpid/test/unit/basic/ObjectMessageTest.java
+++ b/java/client/src/test/java/org/apache/qpid/test/unit/basic/ObjectMessageTest.java
@@ -50,7 +50,7 @@ public class ObjectMessageTest extends TestCase implements MessageListener
TransportConnection.createVMBroker(1);
try
{
- init(new AMQConnection(_connectionString, "guest", "guest", randomize("Client"), "/test_path"));
+ init(new AMQConnection(_connectionString, "guest", "guest", randomize("Client"), "test"));
}
catch (Exception e)
{
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/basic/PropertyValueTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/basic/PropertyValueTest.java
index 17679788bd..d0126e1917 100644
--- a/java/client/src/test/java/org/apache/qpid/test/unit/basic/PropertyValueTest.java
+++ b/java/client/src/test/java/org/apache/qpid/test/unit/basic/PropertyValueTest.java
@@ -29,12 +29,7 @@ import org.apache.qpid.client.AMQSession;
import org.apache.qpid.client.message.JMSTextMessage;
import org.apache.qpid.testutil.VMBrokerSetup;
-import javax.jms.Destination;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageListener;
-import javax.jms.MessageProducer;
-import javax.jms.Queue;
+import javax.jms.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@@ -58,7 +53,7 @@ public class PropertyValueTest extends TestCase implements MessageListener
super.setUp();
try
{
- init(new AMQConnection(_connectionString, "guest", "guest", randomize("Client"), "/test_path"));
+ init(new AMQConnection(_connectionString, "guest", "guest", randomize("Client"), "test"));
}
catch (Exception e)
{
@@ -81,7 +76,7 @@ public class PropertyValueTest extends TestCase implements MessageListener
{
_connection = connection;
_destination = destination;
- _session = (AMQSession) connection.createSession(false, AMQSession.AUTO_ACKNOWLEDGE);
+ _session = (AMQSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
//set up a slow consumer
_session.createConsumer(destination).setMessageListener(this);
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/basic/PubSubTwoConnectionRefTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/basic/PubSubTwoConnectionRefTest.java
new file mode 100644
index 0000000000..c54ea8c6e6
--- /dev/null
+++ b/java/client/src/test/java/org/apache/qpid/test/unit/basic/PubSubTwoConnectionRefTest.java
@@ -0,0 +1,81 @@
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+package org.apache.qpid.test.unit.basic;
+
+import junit.framework.TestCase;
+import org.apache.qpid.client.transport.TransportConnection;
+import org.apache.qpid.client.AMQConnection;
+import org.apache.qpid.client.AMQSession;
+import org.apache.qpid.client.AMQTopic;
+import org.apache.qpid.client.BasicMessageProducer;
+
+import javax.jms.*;
+
+/**
+ * @author Apache Software Foundation
+ */
+public class PubSubTwoConnectionRefTest extends TestCase
+{
+ protected void setUp() throws Exception
+ {
+ super.setUp();
+ TransportConnection.createVMBroker(1);
+ }
+
+ protected void tearDown() throws Exception
+ {
+ super.tearDown();
+ }
+
+ /**
+ * This tests that a consumer is set up synchronously
+ * @throws Exception
+ */
+ public void testTwoConnections() throws Exception
+ {
+ AMQTopic topic = new AMQTopic("MyTopic");
+ AMQConnection con1 = new AMQConnection("vm://:1", "guest", "guest", "Client1", "test");
+ AMQSession session1 = con1.createAMQSession(false, AMQSession.NO_ACKNOWLEDGE);
+ BasicMessageProducer producer = session1.createBasicProducer(topic);
+
+ Connection con2 = new AMQConnection("vm://:1", "guest", "guest", "Client2", "test");
+ Session session2 = con2.createSession(false, AMQSession.NO_ACKNOWLEDGE);
+ MessageConsumer consumer = session2.createConsumer(topic);
+ con2.start();
+ producer.sendRef(session1.createTextMessage("Hello ref"));
+// producer.sendRef(session1.createTextMessage("Goodbye ref"));
+ TextMessage tm1 = (TextMessage) consumer.receive(2000);
+ assertNotNull(tm1);
+ assertEquals("Hello ref", tm1.getText());
+// assertEquals("Goodbye ref", tm1.getText());
+ }
+
+ public static void main(String[] args){
+ PubSubTwoConnectionRefTest test = new PubSubTwoConnectionRefTest();
+ try {
+ test.setUp();
+ test.testTwoConnections();
+ } catch (Exception e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+}
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/basic/PubSubTwoConnectionTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/basic/PubSubTwoConnectionTest.java
index b853963c96..937944e340 100644
--- a/java/client/src/test/java/org/apache/qpid/test/unit/basic/PubSubTwoConnectionTest.java
+++ b/java/client/src/test/java/org/apache/qpid/test/unit/basic/PubSubTwoConnectionTest.java
@@ -51,11 +51,11 @@ public class PubSubTwoConnectionTest extends TestCase
public void testTwoConnections() throws Exception
{
Topic topic = new AMQTopic("MyTopic");
- Connection con1 = new AMQConnection("vm://:1", "guest", "guest", "Client1", "/test_path");
+ Connection con1 = new AMQConnection("vm://:1", "guest", "guest", "Client1", "test");
Session session1 = con1.createSession(false, AMQSession.NO_ACKNOWLEDGE);
MessageProducer producer = session1.createProducer(topic);
- Connection con2 = new AMQConnection("vm://:1", "guest", "guest", "Client2", "/test_path");
+ Connection con2 = new AMQConnection("vm://:1", "guest", "guest", "Client2", "test");
Session session2 = con2.createSession(false, AMQSession.NO_ACKNOWLEDGE);
MessageConsumer consumer = session2.createConsumer(topic);
con2.start();
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/basic/ReceiveTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/basic/ReceiveTest.java
index 302551b05c..1db62cffa9 100644
--- a/java/client/src/test/java/org/apache/qpid/test/unit/basic/ReceiveTest.java
+++ b/java/client/src/test/java/org/apache/qpid/test/unit/basic/ReceiveTest.java
@@ -48,7 +48,7 @@ public class ReceiveTest extends TestCase
{
createVMBroker();
String broker = _connectionString;
- init(new AMQConnection(broker, "guest", "guest", "ReceiveTestClient", "/test_path"));
+ init(new AMQConnection(broker, "guest", "guest", "ReceiveTestClient", "test"));
}
}
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/basic/SelectorTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/basic/SelectorTest.java
index 27a2ccb32e..fe15e151a3 100644
--- a/java/client/src/test/java/org/apache/qpid/test/unit/basic/SelectorTest.java
+++ b/java/client/src/test/java/org/apache/qpid/test/unit/basic/SelectorTest.java
@@ -51,7 +51,7 @@ public class SelectorTest extends TestCase implements MessageListener
{
super.setUp();
TransportConnection.createVMBroker(1);
- init(new AMQConnection(_connectionString, "guest", "guest", randomize("Client"), "/test_path"));
+ init(new AMQConnection(_connectionString, "guest", "guest", randomize("Client"), "test"));
}
protected void tearDown() throws Exception
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/basic/SessionStartTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/basic/SessionStartTest.java
index 726c7e39d7..cce02accd8 100644
--- a/java/client/src/test/java/org/apache/qpid/test/unit/basic/SessionStartTest.java
+++ b/java/client/src/test/java/org/apache/qpid/test/unit/basic/SessionStartTest.java
@@ -43,7 +43,7 @@ public class SessionStartTest extends TestCase implements MessageListener
protected void setUp() throws Exception
{
super.setUp();
- init(new AMQConnection(_connectionString, "guest", "guest", randomize("Client"), "/test_path"));
+ init(new AMQConnection(_connectionString, "guest", "guest", randomize("Client"), "test"));
}
protected void tearDown() throws Exception
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/basic/TextMessageTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/basic/TextMessageTest.java
index 903f6a9da9..b50cd39780 100644
--- a/java/client/src/test/java/org/apache/qpid/test/unit/basic/TextMessageTest.java
+++ b/java/client/src/test/java/org/apache/qpid/test/unit/basic/TextMessageTest.java
@@ -52,7 +52,7 @@ public class TextMessageTest extends TestCase implements MessageListener
super.setUp();
try
{
- init(new AMQConnection(_connectionString, "guest", "guest", randomize("Client"), "/test_path"));
+ init(new AMQConnection(_connectionString, "guest", "guest", randomize("Client"), "test"));
}
catch (Exception e)
{
@@ -75,7 +75,7 @@ public class TextMessageTest extends TestCase implements MessageListener
{
_connection = connection;
_destination = destination;
- _session = (AMQSession) connection.createSession(false, AMQSession.AUTO_ACKNOWLEDGE);
+ _session = (AMQSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
//set up a slow consumer
_session.createConsumer(destination).setMessageListener(this);
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/client/AMQConnectionTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/client/AMQConnectionTest.java
index 68bdc6ddf2..db4e18a4a1 100644
--- a/java/client/src/test/java/org/apache/qpid/test/unit/client/AMQConnectionTest.java
+++ b/java/client/src/test/java/org/apache/qpid/test/unit/client/AMQConnectionTest.java
@@ -24,7 +24,7 @@ import org.apache.qpid.client.AMQTopic;
import org.apache.qpid.client.AMQConnection;
import org.apache.qpid.client.AMQQueue;
import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.testutil.VMBrokerSetup;
+import org.apache.qpid.client.transport.TransportConnection;
import javax.jms.*;
@@ -41,13 +41,15 @@ public class AMQConnectionTest extends TestCase
protected void setUp() throws Exception
{
super.setUp();
- _connection = new AMQConnection("vm://:1", "guest", "guest", "fred", "/test");
+ TransportConnection.createVMBroker(1);
+ _connection = new AMQConnection("vm://:1", "guest", "guest", "fred", "test");
_topic = new AMQTopic("mytopic");
_queue = new AMQQueue("myqueue");
}
protected void tearDown() throws Exception
{
+ super.tearDown();
try
{
_connection.close();
@@ -55,8 +57,8 @@ public class AMQConnectionTest extends TestCase
catch (JMSException e)
{
//ignore
- }
- super.tearDown();
+ }
+ TransportConnection.killAllVMBrokers();
}
/**
@@ -195,6 +197,6 @@ public class AMQConnectionTest extends TestCase
public static junit.framework.Test suite()
{
- return new VMBrokerSetup(new junit.framework.TestSuite(AMQConnectionTest.class));
+ return new junit.framework.TestSuite(AMQConnectionTest.class);
}
}
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/client/AMQSessionTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/client/AMQSessionTest.java
index 67c4f1dd6b..b01a129bf2 100644
--- a/java/client/src/test/java/org/apache/qpid/test/unit/client/AMQSessionTest.java
+++ b/java/client/src/test/java/org/apache/qpid/test/unit/client/AMQSessionTest.java
@@ -46,7 +46,7 @@ public class AMQSessionTest extends TestCase
protected void setUp() throws Exception
{
super.setUp();
- _connection = new AMQConnection("vm://:1", "guest", "guest", "fred", "/test");
+ _connection = new AMQConnection("vm://:1", "guest", "guest", "fred", "test");
_topic = new AMQTopic("mytopic");
_queue = new AMQQueue("myqueue");
_session = (AMQSession) _connection.createSession(false, AMQSession.NO_ACKNOWLEDGE);
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/client/channelclose/ChannelCloseOkTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/client/channelclose/ChannelCloseOkTest.java
index ac789eb915..05d83be47f 100644
--- a/java/client/src/test/java/org/apache/qpid/test/unit/client/channelclose/ChannelCloseOkTest.java
+++ b/java/client/src/test/java/org/apache/qpid/test/unit/client/channelclose/ChannelCloseOkTest.java
@@ -20,17 +20,17 @@
*/
package org.apache.qpid.test.unit.client.channelclose;
+import junit.framework.TestCase;
+import junit.textui.TestRunner;
+import org.apache.log4j.Logger;
import org.apache.qpid.client.AMQConnection;
import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.testutil.VMBrokerSetup;
-import org.apache.log4j.Logger;
+import org.apache.qpid.client.transport.TransportConnection;
import javax.jms.*;
import java.util.ArrayList;
import java.util.List;
-import junit.framework.TestCase;
-import junit.textui.TestRunner;
/**
* Due to bizarre exception handling all sessions are closed if you get
@@ -64,7 +64,8 @@ public class ChannelCloseOkTest extends TestCase
{
super.setUp();
- _connection = new AMQConnection(_connectionString, "guest", "guest", randomize("Client"), "/test_path");
+ TransportConnection.createVMBroker(1);
+ _connection = new AMQConnection(_connectionString, "guest", "guest", randomize("Client"), "test");
_destination1 = new AMQQueue("q1", true);
_destination2 = new AMQQueue("q2", true);
@@ -192,7 +193,15 @@ public class ChannelCloseOkTest extends TestCase
{
while (received.size() < count)
{
- received.wait();
+ try
+ {
+ received.wait();
+ }
+ catch (InterruptedException e)
+ {
+ _log.info("Interrupted: " + e);
+ throw e;
+ }
}
}
}
@@ -209,6 +218,6 @@ public class ChannelCloseOkTest extends TestCase
public static junit.framework.Test suite()
{
- return new VMBrokerSetup(new junit.framework.TestSuite(ChannelCloseOkTest.class));
+ return new junit.framework.TestSuite(ChannelCloseOkTest.class);
}
}
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/client/channelclose/CloseWithBlockingReceiveTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/client/channelclose/CloseWithBlockingReceiveTest.java
index 0b3ed931f8..7a665daeb3 100644
--- a/java/client/src/test/java/org/apache/qpid/test/unit/client/channelclose/CloseWithBlockingReceiveTest.java
+++ b/java/client/src/test/java/org/apache/qpid/test/unit/client/channelclose/CloseWithBlockingReceiveTest.java
@@ -49,7 +49,7 @@ public class CloseWithBlockingReceiveTest extends TestCase
public void testReceiveReturnsNull() throws Exception
{
final Connection connection = new AMQConnection("vm://:1", "guest", "guest",
- "fred", "/test");
+ "fred", "test");
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageConsumer consumer = session.createConsumer(new AMQTopic("banana"));
connection.start();
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/client/connection/ConnectionTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/client/connection/ConnectionTest.java
index c7fc3efc87..2ee9fad5d4 100644
--- a/java/client/src/test/java/org/apache/qpid/test/unit/client/connection/ConnectionTest.java
+++ b/java/client/src/test/java/org/apache/qpid/test/unit/client/connection/ConnectionTest.java
@@ -26,6 +26,7 @@ import org.apache.qpid.client.transport.TransportConnection;
import org.apache.qpid.AMQException;
import org.apache.qpid.AMQConnectionFailureException;
import org.apache.qpid.AMQUnresolvedAddressException;
+import org.apache.qpid.AMQConnectionFailureException;
import javax.jms.Connection;
@@ -47,14 +48,15 @@ public class ConnectionTest extends TestCase
protected void tearDown() throws Exception
{
- TransportConnection.killAllVMBrokers();
+ TransportConnection.killVMBroker(1);
}
public void testSimpleConnection()
{
try
{
- new AMQConnection(_broker, "guest", "guest", "fred", "/test");
+ AMQConnection conn = new AMQConnection(_broker, "guest", "guest", "fred", "test");
+ conn.close();
}
catch (Exception e)
{
@@ -93,6 +95,7 @@ public class ConnectionTest extends TestCase
fail("Correct exception not thrown. Excpected 'AMQConnectionFailureException' got: " + amqe);
}
}
+
}
public void testUnresolvedHostFailure() throws Exception
@@ -114,7 +117,7 @@ public class ConnectionTest extends TestCase
public void testClientIdCannotBeChanged() throws Exception
{
Connection connection = new AMQConnection(_broker, "guest", "guest",
- "fred", "/test");
+ "fred", "test");
try
{
connection.setClientID("someClientId");
@@ -129,7 +132,7 @@ public class ConnectionTest extends TestCase
public void testClientIdIsPopulatedAutomatically() throws Exception
{
Connection connection = new AMQConnection(_broker, "guest", "guest",
- null, "/test");
+ null, "test");
assertNotNull(connection.getClientID());
}
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/client/connectionurl/ConnectionURLTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/client/connectionurl/ConnectionURLTest.java
index 147d2ae43e..a23c78822f 100644
--- a/java/client/src/test/java/org/apache/qpid/test/unit/client/connectionurl/ConnectionURLTest.java
+++ b/java/client/src/test/java/org/apache/qpid/test/unit/client/connectionurl/ConnectionURLTest.java
@@ -33,14 +33,14 @@ public class ConnectionURLTest extends TestCase
public void testFailoverURL() throws URLSyntaxException
{
- String url = "amqp://ritchiem:bob@/temp?brokerlist='tcp://localhost:5672;tcp://fancyserver:3000/',failover='roundrobin'";
+ String url = "amqp://ritchiem:bob@/test?brokerlist='tcp://localhost:5672;tcp://fancyserver:3000/',failover='roundrobin'";
ConnectionURL connectionurl = new AMQConnectionURL(url);
assertTrue(connectionurl.getFailoverMethod().equals("roundrobin"));
assertTrue(connectionurl.getUsername().equals("ritchiem"));
assertTrue(connectionurl.getPassword().equals("bob"));
- assertTrue(connectionurl.getVirtualHost().equals("/temp"));
+ assertTrue(connectionurl.getVirtualHost().equals("/test"));
assertTrue(connectionurl.getBrokerCount() == 2);
@@ -60,14 +60,14 @@ public class ConnectionURLTest extends TestCase
public void testSingleTransportUsernamePasswordURL() throws URLSyntaxException
{
- String url = "amqp://ritchiem:bob@/temp?brokerlist='tcp://localhost:5672'";
+ String url = "amqp://ritchiem:bob@/test?brokerlist='tcp://localhost:5672'";
ConnectionURL connectionurl = new AMQConnectionURL(url);
assertTrue(connectionurl.getFailoverMethod() == null);
assertTrue(connectionurl.getUsername().equals("ritchiem"));
assertTrue(connectionurl.getPassword().equals("bob"));
- assertTrue(connectionurl.getVirtualHost().equals("/temp"));
+ assertTrue(connectionurl.getVirtualHost().equals("/test"));
assertTrue(connectionurl.getBrokerCount() == 1);
@@ -80,14 +80,14 @@ public class ConnectionURLTest extends TestCase
public void testSingleTransportUsernameBlankPasswordURL() throws URLSyntaxException
{
- String url = "amqp://ritchiem:@/temp?brokerlist='tcp://localhost:5672'";
+ String url = "amqp://ritchiem:@/test?brokerlist='tcp://localhost:5672'";
ConnectionURL connectionurl = new AMQConnectionURL(url);
assertTrue(connectionurl.getFailoverMethod() == null);
assertTrue(connectionurl.getUsername().equals("ritchiem"));
assertTrue(connectionurl.getPassword().equals(""));
- assertTrue(connectionurl.getVirtualHost().equals("/temp"));
+ assertTrue(connectionurl.getVirtualHost().equals("/test"));
assertTrue(connectionurl.getBrokerCount() == 1);
@@ -100,7 +100,7 @@ public class ConnectionURLTest extends TestCase
public void testFailedURLNullPassword()
{
- String url = "amqp://ritchiem@/temp?brokerlist='tcp://localhost:5672'";
+ String url = "amqp://ritchiem@/test?brokerlist='tcp://localhost:5672'";
try
{
@@ -140,7 +140,7 @@ public class ConnectionURLTest extends TestCase
public void testSingleTransportWithClientURLURL() throws URLSyntaxException
{
- String url = "amqp://guest:guest@clientname/temp?brokerlist='tcp://localhost:5672'";
+ String url = "amqp://guest:guest@clientname/test?brokerlist='tcp://localhost:5672'";
ConnectionURL connectionurl = new AMQConnectionURL(url);
@@ -148,7 +148,7 @@ public class ConnectionURLTest extends TestCase
assertTrue(connectionurl.getFailoverMethod() == null);
assertTrue(connectionurl.getUsername().equals("guest"));
assertTrue(connectionurl.getPassword().equals("guest"));
- assertTrue(connectionurl.getVirtualHost().equals("/temp"));
+ assertTrue(connectionurl.getVirtualHost().equals("/test"));
assertTrue(connectionurl.getClientName().equals("clientname"));
@@ -164,14 +164,14 @@ public class ConnectionURLTest extends TestCase
public void testSingleTransport1OptionURL() throws URLSyntaxException
{
- String url = "amqp://guest:guest@/temp?brokerlist='tcp://localhost:5672',routingkey='jim'";
+ String url = "amqp://guest:guest@/test?brokerlist='tcp://localhost:5672',routingkey='jim'";
ConnectionURL connectionurl = new AMQConnectionURL(url);
assertTrue(connectionurl.getFailoverMethod() == null);
assertTrue(connectionurl.getUsername().equals("guest"));
assertTrue(connectionurl.getPassword().equals("guest"));
- assertTrue(connectionurl.getVirtualHost().equals("/temp"));
+ assertTrue(connectionurl.getVirtualHost().equals("/test"));
assertTrue(connectionurl.getBrokerCount() == 1);
@@ -187,14 +187,14 @@ public class ConnectionURLTest extends TestCase
public void testSingleTransportDefaultedBroker() throws URLSyntaxException
{
- String url = "amqp://guest:guest@/temp?brokerlist='localhost'";
+ String url = "amqp://guest:guest@/test?brokerlist='localhost'";
ConnectionURL connectionurl = new AMQConnectionURL(url);
assertTrue(connectionurl.getFailoverMethod() == null);
assertTrue(connectionurl.getUsername().equals("guest"));
assertTrue(connectionurl.getPassword().equals("guest"));
- assertTrue(connectionurl.getVirtualHost().equals("/temp"));
+ assertTrue(connectionurl.getVirtualHost().equals("/test"));
assertTrue(connectionurl.getBrokerCount() == 1);
@@ -207,17 +207,83 @@ public class ConnectionURLTest extends TestCase
assertTrue(service.getPort() == 5672);
}
+ public void testSingleTransportDefaultedBrokerWithPort() throws URLSyntaxException
+ {
+ String url = "amqp://guest:guest@/test?brokerlist='localhost:1234'";
+
+ ConnectionURL connectionurl = new AMQConnectionURL(url);
+
+ assertTrue(connectionurl.getFailoverMethod() == null);
+ assertTrue(connectionurl.getUsername().equals("guest"));
+ assertTrue(connectionurl.getPassword().equals("guest"));
+ assertTrue(connectionurl.getVirtualHost().equals("/test"));
+
+
+ assertTrue(connectionurl.getBrokerCount() == 1);
+
+ BrokerDetails service = connectionurl.getBrokerDetails(0);
+
+ assertTrue(service.getTransport().equals("tcp"));
+
+ assertTrue(service.getHost().equals("localhost"));
+ assertTrue(service.getPort() == 1234);
+ }
+
+ public void testSingleTransportDefaultedBrokerWithIP() throws URLSyntaxException
+ {
+ String url = "amqp://guest:guest@/test?brokerlist='127.0.0.1'";
+
+ ConnectionURL connectionurl = new AMQConnectionURL(url);
+
+ assertTrue(connectionurl.getFailoverMethod() == null);
+ assertTrue(connectionurl.getUsername().equals("guest"));
+ assertTrue(connectionurl.getPassword().equals("guest"));
+ assertTrue(connectionurl.getVirtualHost().equals("/test"));
+
+
+ assertTrue(connectionurl.getBrokerCount() == 1);
+
+ BrokerDetails service = connectionurl.getBrokerDetails(0);
+
+ assertTrue(service.getTransport().equals("tcp"));
+
+ assertTrue(service.getHost().equals("127.0.0.1"));
+ assertTrue(service.getPort() == 5672);
+ }
+
+ public void testSingleTransportDefaultedBrokerWithIPandPort() throws URLSyntaxException
+ {
+ String url = "amqp://guest:guest@/test?brokerlist='127.0.0.1:1234'";
+
+// ConnectionURL connectionurl = new AMQConnectionURL(url);
+//
+// assertTrue(connectionurl.getFailoverMethod() == null);
+// assertTrue(connectionurl.getUsername().equals("guest"));
+// assertTrue(connectionurl.getPassword().equals("guest"));
+// assertTrue(connectionurl.getVirtualHost().equals("/temp"));
+//
+//
+// assertTrue(connectionurl.getBrokerCount() == 1);
+//
+// BrokerDetails service = connectionurl.getBrokerDetails(0);
+//
+// assertTrue(service.getTransport().equals("tcp"));
+//
+// assertTrue(service.getHost().equals("127.0.0.1"));
+// assertTrue(service.getPort() == 1234);
+ }
+
public void testSingleTransportMultiOptionURL() throws URLSyntaxException
{
- String url = "amqp://guest:guest@/temp?brokerlist='tcp://localhost:5672',routingkey='jim',timeout='200',immediatedelivery='true'";
+ String url = "amqp://guest:guest@/test?brokerlist='tcp://localhost:5672',routingkey='jim',timeout='200',immediatedelivery='true'";
ConnectionURL connectionurl = new AMQConnectionURL(url);
assertTrue(connectionurl.getFailoverMethod() == null);
assertTrue(connectionurl.getUsername().equals("guest"));
assertTrue(connectionurl.getPassword().equals("guest"));
- assertTrue(connectionurl.getVirtualHost().equals("/temp"));
+ assertTrue(connectionurl.getVirtualHost().equals("/test"));
assertTrue(connectionurl.getBrokerCount() == 1);
@@ -235,14 +301,14 @@ public class ConnectionURLTest extends TestCase
public void testSinglevmURL() throws URLSyntaxException
{
- String url = "amqp://guest:guest@/messages?brokerlist='vm://:2'";
+ String url = "amqp://guest:guest@/test?brokerlist='vm://:2'";
ConnectionURL connectionurl = new AMQConnectionURL(url);
assertTrue(connectionurl.getFailoverMethod() == null);
assertTrue(connectionurl.getUsername().equals("guest"));
assertTrue(connectionurl.getPassword().equals("guest"));
- assertTrue(connectionurl.getVirtualHost().equals("/messages"));
+ assertTrue(connectionurl.getVirtualHost().equals("/test"));
assertTrue(connectionurl.getBrokerCount() == 1);
@@ -256,14 +322,14 @@ public class ConnectionURLTest extends TestCase
public void testFailoverVMURL() throws URLSyntaxException
{
- String url = "amqp://ritchiem:bob@/temp?brokerlist='vm://:2;vm://:3',failover='roundrobin'";
+ String url = "amqp://ritchiem:bob@/test?brokerlist='vm://:2;vm://:3',failover='roundrobin'";
ConnectionURL connectionurl = new AMQConnectionURL(url);
assertTrue(connectionurl.getFailoverMethod().equals("roundrobin"));
assertTrue(connectionurl.getUsername().equals("ritchiem"));
assertTrue(connectionurl.getPassword().equals("bob"));
- assertTrue(connectionurl.getVirtualHost().equals("/temp"));
+ assertTrue(connectionurl.getVirtualHost().equals("/test"));
assertTrue(connectionurl.getBrokerCount() == 2);
@@ -309,7 +375,6 @@ public class ConnectionURLTest extends TestCase
}
-
public void testWrongOptionSeparatorInOptions()
{
String url = "amqp://guest:guest@/test?brokerlist='tcp://localhost:5672;tcp://localhost:5673'+failover='roundrobin'";
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/client/forwardall/Client.java b/java/client/src/test/java/org/apache/qpid/test/unit/client/forwardall/Client.java
index 6c2c684362..db0d3e0eab 100644
--- a/java/client/src/test/java/org/apache/qpid/test/unit/client/forwardall/Client.java
+++ b/java/client/src/test/java/org/apache/qpid/test/unit/client/forwardall/Client.java
@@ -65,29 +65,35 @@ public class Client implements MessageListener
_connection.close();
}
- public void onMessage(Message response)
+ public synchronized void onMessage(Message response)
{
+
System.out.println("Received " + (++_count) + " of " + _expected + " responses.");
if(_count == _expected)
{
- synchronized(this)
- {
- notifyAll();
- }
+
+ notifyAll();
}
+
+
}
- synchronized void waitUntilComplete() throws InterruptedException
+ synchronized void waitUntilComplete() throws Exception
{
- while(_count < _expected)
+
+ if(_count < _expected)
+ {
+ wait(10000L);
+ }
+ if(_count < _expected)
{
- wait();
+ throw new Exception("Didn't receive all messages... got " + _count + " expected " + _expected);
}
}
static AMQConnection connect(String broker) throws Exception
{
- return new AMQConnection(broker, "guest", "guest", "Client" + System.currentTimeMillis(), "/test_path");
+ return new AMQConnection(broker, "guest", "guest", "Client" + System.currentTimeMillis(), "test");
}
public static void main(String[] argv) throws Exception
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/client/forwardall/Service.java b/java/client/src/test/java/org/apache/qpid/test/unit/client/forwardall/Service.java
index a1c64e2246..58f9c6fc19 100644
--- a/java/client/src/test/java/org/apache/qpid/test/unit/client/forwardall/Service.java
+++ b/java/client/src/test/java/org/apache/qpid/test/unit/client/forwardall/Service.java
@@ -73,7 +73,7 @@ public class Service implements MessageListener
static AMQConnection connect(String broker) throws Exception
{
- return new AMQConnection(broker, "guest", "guest", "Client" + System.currentTimeMillis(), "/test_path");
+ return new AMQConnection(broker, "guest", "guest", "Client" + System.currentTimeMillis(), "test");
}
// public static void main(String[] argv) throws Exception
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/client/forwardall/SpecialQueue.java b/java/client/src/test/java/org/apache/qpid/test/unit/client/forwardall/SpecialQueue.java
index 22015dbc93..691acbb213 100644
--- a/java/client/src/test/java/org/apache/qpid/test/unit/client/forwardall/SpecialQueue.java
+++ b/java/client/src/test/java/org/apache/qpid/test/unit/client/forwardall/SpecialQueue.java
@@ -21,6 +21,7 @@
package org.apache.qpid.test.unit.client.forwardall;
import org.apache.qpid.client.AMQQueue;
+import org.apache.qpid.framing.AMQShortString;
/**
* Queue that allows several private queues to be registered and bound
@@ -29,15 +30,19 @@ import org.apache.qpid.client.AMQQueue;
*/
class SpecialQueue extends AMQQueue
{
- private final String name;
+ private final AMQShortString name;
SpecialQueue(String name)
{
+ this(new AMQShortString(name));
+ }
+ SpecialQueue(AMQShortString name)
+ {
super(name, true);
this.name = name;
}
- public String getRoutingKey()
+ public AMQShortString getRoutingKey()
{
return name;
}
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/client/message/ObjectMessageTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/client/message/ObjectMessageTest.java
index bbd1870168..0e4603ed24 100644
--- a/java/client/src/test/java/org/apache/qpid/test/unit/client/message/ObjectMessageTest.java
+++ b/java/client/src/test/java/org/apache/qpid/test/unit/client/message/ObjectMessageTest.java
@@ -54,7 +54,7 @@ public class ObjectMessageTest extends TestCase implements MessageListener
protected void setUp() throws Exception
{
super.setUp();
- connection = new AMQConnection(_broker, "guest", "guest", randomize("Client"), "/test_path");
+ connection = new AMQConnection(_broker, "guest", "guest", randomize("Client"), "test");
destination = new AMQQueue(randomize("LatencyTest"), true);
session = (AMQSession) connection.createSession(false, AMQSession.NO_ACKNOWLEDGE);
@@ -101,6 +101,7 @@ public class ObjectMessageTest extends TestCase implements MessageListener
}
catch (Exception e)
{
+ e.printStackTrace();
fail("This Test should succeed but failed due to: " + e);
}
finally
@@ -236,7 +237,7 @@ public class ObjectMessageTest extends TestCase implements MessageListener
public void onMessage(Message message)
{
- received++;
+
try
{
if (message instanceof ObjectMessage)
@@ -255,13 +256,11 @@ public class ObjectMessageTest extends TestCase implements MessageListener
items.add(e);
}
- if (waiting)
- {
synchronized(this)
{
+ received++;
notify();
}
- }
}
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/client/protocol/AMQProtocolSessionTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/client/protocol/AMQProtocolSessionTest.java
index eee9b2de9f..64898a1b9a 100644
--- a/java/client/src/test/java/org/apache/qpid/test/unit/client/protocol/AMQProtocolSessionTest.java
+++ b/java/client/src/test/java/org/apache/qpid/test/unit/client/protocol/AMQProtocolSessionTest.java
@@ -23,6 +23,7 @@ package org.apache.qpid.test.unit.client.protocol;
import org.apache.qpid.client.AMQConnection;
import org.apache.qpid.client.protocol.AMQProtocolHandler;
import org.apache.qpid.client.protocol.AMQProtocolSession;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.mina.common.IoSession;
import junit.framework.TestCase;
@@ -45,7 +46,7 @@ public class AMQProtocolSessionTest extends TestCase
return (TestIoSession) _minaProtocolSession;
}
- public String genQueueName()
+ public AMQShortString genQueueName()
{
return generateQueueName();
}
@@ -80,26 +81,26 @@ public class AMQProtocolSessionTest extends TestCase
public void testGenerateQueueName()
{
- String testAddress;
+ AMQShortString testAddress;
- //test address with / and ; chars which generateQueueName should remove
+ //test address with / and ; chars which generateQueueName should removeKey
_testSession.getMinaProtocolSession().setStringLocalAddress(_brokenAddress);
_testSession.getMinaProtocolSession().setLocalPort(_port);
testAddress = _testSession.genQueueName();
- assertEquals("Failure when generating a queue exchange from an address with special chars",_generatedAddress,testAddress);
+ assertEquals("Failure when generating a queue exchange from an address with special chars",_generatedAddress,testAddress.toString());
//test empty address
_testSession.getMinaProtocolSession().setStringLocalAddress(_emptyAddress);
testAddress = _testSession.genQueueName();
- assertEquals("Failure when generating a queue exchange from an empty address",_generatedAddress_2,testAddress);
+ assertEquals("Failure when generating a queue exchange from an empty address",_generatedAddress_2,testAddress.toString());
//test address with no special chars
_testSession.getMinaProtocolSession().setStringLocalAddress(_validAddress);
testAddress = _testSession.genQueueName();
- assertEquals("Failure when generating a queue exchange from an address with no special chars",_generatedAddress_3,testAddress);
+ assertEquals("Failure when generating a queue exchange from an address with no special chars",_generatedAddress_3,testAddress.toString());
}
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/client/temporaryqueue/TemporaryQueueTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/client/temporaryqueue/TemporaryQueueTest.java
index 6c064e3853..b6c539d91c 100644
--- a/java/client/src/test/java/org/apache/qpid/test/unit/client/temporaryqueue/TemporaryQueueTest.java
+++ b/java/client/src/test/java/org/apache/qpid/test/unit/client/temporaryqueue/TemporaryQueueTest.java
@@ -28,7 +28,7 @@ public class TemporaryQueueTest extends TestCase
protected Connection createConnection() throws AMQException, URLSyntaxException
{
return new AMQConnection(_broker, "guest", "guest",
- "fred", "/test");
+ "fred", "test");
}
public void testTempoaryQueue() throws Exception
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/close/TopicPublisherCloseTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/close/TopicPublisherCloseTest.java
index c9240e9be7..7cbd4e8bdd 100644
--- a/java/client/src/test/java/org/apache/qpid/test/unit/close/TopicPublisherCloseTest.java
+++ b/java/client/src/test/java/org/apache/qpid/test/unit/close/TopicPublisherCloseTest.java
@@ -51,7 +51,7 @@ public class TopicPublisherCloseTest extends TestCase
public void testAllMethodsThrowAfterConnectionClose() throws Exception
{
- AMQConnection connection = new AMQConnection(_connectionString, "guest", "guest", "Client", "/test_path");
+ AMQConnection connection = new AMQConnection(_connectionString, "guest", "guest", "Client", "test");
Topic destination1 = new AMQTopic("t1");
TopicSession session1 = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/message/JMSDestinationTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/message/JMSDestinationTest.java
index c14b5317c7..1f53d7de65 100644
--- a/java/client/src/test/java/org/apache/qpid/test/unit/message/JMSDestinationTest.java
+++ b/java/client/src/test/java/org/apache/qpid/test/unit/message/JMSDestinationTest.java
@@ -11,6 +11,7 @@ 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 org.apache.qpid.framing.AMQShortString;
import javax.jms.*;
@@ -39,12 +40,12 @@ public class JMSDestinationTest extends TestCase
public void testJMSDestination() throws Exception
{
- Connection con = new AMQConnection("vm://:1", "guest", "guest", "consumer1", "/test");
+ Connection con = new AMQConnection("vm://:1", "guest", "guest", "consumer1", "test");
AMQSession consumerSession = (AMQSession) con.createSession(false, Session.CLIENT_ACKNOWLEDGE);
- Queue queue = new AMQQueue("someQ", "someQ", false, true);
+ Queue queue = new AMQQueue(new AMQShortString("someQ"), new AMQShortString("someQ"), false, true);
MessageConsumer consumer = consumerSession.createConsumer(queue);
- Connection con2 = new AMQConnection("vm://:1", "guest", "guest", "producer1", "/test");
+ Connection con2 = new AMQConnection("vm://:1", "guest", "guest", "producer1", "test");
Session producerSession = con2.createSession(false, Session.CLIENT_ACKNOWLEDGE);
MessageProducer producer = producerSession.createProducer(queue);
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/message/JMSPropertiesTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/message/JMSPropertiesTest.java
new file mode 100644
index 0000000000..c09d2504eb
--- /dev/null
+++ b/java/client/src/test/java/org/apache/qpid/test/unit/message/JMSPropertiesTest.java
@@ -0,0 +1,100 @@
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+package org.apache.qpid.test.unit.message;
+
+import junit.framework.TestCase;
+import org.apache.log4j.Logger;
+import org.apache.qpid.client.transport.TransportConnection;
+import org.apache.qpid.client.AMQConnection;
+import org.apache.qpid.client.AMQSession;
+import org.apache.qpid.client.AMQQueue;
+import org.apache.qpid.client.message.TestNonQpidTextMessage;
+import org.apache.qpid.framing.AMQShortString;
+
+import javax.jms.*;
+
+/**
+ * @author Apache Software Foundation
+ */
+public class JMSPropertiesTest extends TestCase
+{
+
+ private static final Logger _logger = Logger.getLogger(JMSPropertiesTest.class);
+
+ public String _connectionString = "vm://:1";
+
+ public static final String JMS_CORR_ID = "QPIDID_01";
+ public static final int JMS_DELIV_MODE = 1;
+ public static final String JMS_TYPE = "test.jms.type";
+ public static final Destination JMS_REPLY_TO = new AMQQueue("my.replyto");
+
+ protected void setUp() throws Exception
+ {
+ super.setUp();
+ TransportConnection.createVMBroker(1);
+ }
+
+
+ protected void tearDown() throws Exception
+ {
+ super.tearDown();
+ TransportConnection.killAllVMBrokers();
+ }
+
+ public void testJMSProperties() throws Exception
+ {
+ Connection con = new AMQConnection("vm://:1", "guest", "guest", "consumer1", "test");
+ AMQSession consumerSession = (AMQSession) con.createSession(false, Session.CLIENT_ACKNOWLEDGE);
+ Queue queue = new AMQQueue(new AMQShortString("someQ"), new AMQShortString("someQ"), false, true);
+ MessageConsumer consumer = consumerSession.createConsumer(queue);
+
+ Connection con2 = new AMQConnection("vm://:1", "guest", "guest", "producer1", "test");
+ Session producerSession = con2.createSession(false, Session.CLIENT_ACKNOWLEDGE);
+ MessageProducer producer = producerSession.createProducer(queue);
+
+ //create a test message to send
+ ObjectMessage sentMsg = new TestNonQpidTextMessage();
+ sentMsg.setJMSCorrelationID(JMS_CORR_ID);
+ sentMsg.setJMSDeliveryMode(JMS_DELIV_MODE);
+ sentMsg.setJMSType(JMS_TYPE);
+ sentMsg.setJMSReplyTo(JMS_REPLY_TO);
+
+ //send it
+ producer.send(sentMsg);
+
+ con2.close();
+
+ con.start();
+
+ //get message and check JMS properties
+ ObjectMessage rm = (ObjectMessage) consumer.receive();
+ assertNotNull(rm);
+
+ assertEquals("JMS Correlation ID mismatch",sentMsg.getJMSCorrelationID(),rm.getJMSCorrelationID());
+ //TODO: Commented out as always overwritten by send delivery mode value - prob should not set in conversion
+ //assertEquals("JMS Delivery Mode mismatch",sentMsg.getJMSDeliveryMode(),rm.getJMSDeliveryMode());
+ assertEquals("JMS Type mismatch",sentMsg.getJMSType(),rm.getJMSType());
+ assertEquals("JMS Reply To mismatch",sentMsg.getJMSReplyTo(),rm.getJMSReplyTo());
+
+ con.close();
+ }
+
+}
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/message/MessageConverterTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/message/MessageConverterTest.java
new file mode 100644
index 0000000000..6a335b8627
--- /dev/null
+++ b/java/client/src/test/java/org/apache/qpid/test/unit/message/MessageConverterTest.java
@@ -0,0 +1,109 @@
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+package org.apache.qpid.test.unit.message;
+
+import junit.framework.TestCase;
+import org.apache.qpid.client.message.MessageConverter;
+import org.apache.qpid.client.message.JMSTextMessage;
+import org.apache.qpid.client.message.AbstractJMSMessage;
+import org.apache.qpid.client.message.JMSMapMessage;
+import org.apache.qpid.client.AMQQueue;
+
+import javax.jms.Message;
+import javax.jms.Destination;
+import javax.jms.TextMessage;
+import javax.jms.MapMessage;
+import java.util.HashMap;
+
+
+public class MessageConverterTest extends TestCase {
+
+ public static final String JMS_CORR_ID = "QPIDID_01";
+ public static final int JMS_DELIV_MODE = 1;
+ public static final String JMS_TYPE = "test.jms.type";
+ public static final Destination JMS_REPLY_TO = new AMQQueue("my.replyto");
+
+ protected JMSTextMessage testTextMessage;
+
+ protected JMSMapMessage testMapMessage;
+
+ protected void setUp() throws Exception
+ {
+ super.setUp();
+ testTextMessage = new JMSTextMessage();
+
+ //Add JMSProperties
+ testTextMessage.setJMSCorrelationID(JMS_CORR_ID);
+ testTextMessage.setJMSDeliveryMode(JMS_DELIV_MODE);
+ testTextMessage.setJMSType(JMS_TYPE);
+ testTextMessage.setJMSReplyTo(JMS_REPLY_TO);
+ testTextMessage.setText("testTextMessage text");
+
+ //Add non-JMS properties
+ testTextMessage.setStringProperty("testProp1","testValue1");
+ testTextMessage.setDoubleProperty("testProp2",Double.MIN_VALUE);
+
+ testMapMessage = new JMSMapMessage();
+ testMapMessage.setString("testMapString","testMapStringValue");
+ testMapMessage.setDouble("testMapDouble",Double.MAX_VALUE);
+ }
+
+ public void testSetProperties() throws Exception
+ {
+ AbstractJMSMessage newMessage = new MessageConverter((TextMessage)testTextMessage).getConvertedMessage();
+
+ //check JMS prop values on newMessage match
+ assertEquals("JMS Correlation ID mismatch",testTextMessage.getJMSCorrelationID(),newMessage.getJMSCorrelationID());
+ assertEquals("JMS Delivery mode mismatch",testTextMessage.getJMSDeliveryMode(),newMessage.getJMSDeliveryMode());
+ assertEquals("JMS Type mismatch",testTextMessage.getJMSType(),newMessage.getJMSType());
+ assertEquals("JMS Reply To mismatch",testTextMessage.getJMSReplyTo(),newMessage.getJMSReplyTo());
+
+ //check non-JMS standard props ok too
+ assertEquals("Test String prop value mismatch",testTextMessage.getStringProperty("testProp1"),
+ newMessage.getStringProperty("testProp1"));
+ assertEquals("Test Double prop value mismatch",testTextMessage.getDoubleProperty("testProp2"),
+ newMessage.getDoubleProperty("testProp2"));
+ }
+
+ public void testJMSTextMessageConversion() throws Exception
+ {
+ AbstractJMSMessage newMessage = new MessageConverter((TextMessage)testTextMessage).getConvertedMessage();
+ assertEquals("Converted message text mismatch",((JMSTextMessage)newMessage).getText(),testTextMessage.getText());
+ }
+
+ public void testJMSMapMessageConversion() throws Exception
+ {
+ AbstractJMSMessage newMessage = new MessageConverter((MapMessage)testMapMessage).getConvertedMessage();
+ assertEquals("Converted map message String mismatch",((JMSMapMessage)newMessage).getString("testMapString"),
+ testMapMessage.getString("testMapString"));
+ assertEquals("Converted map message Double mismatch",((JMSMapMessage)newMessage).getDouble("testMapDouble"),
+ testMapMessage.getDouble("testMapDouble"));
+
+ }
+
+ protected void tearDown() throws Exception
+ {
+ super.tearDown();
+ testTextMessage = null;
+ }
+
+
+}
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/message/StreamMessageTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/message/StreamMessageTest.java
index 184d7cb015..7d83d19d74 100644
--- a/java/client/src/test/java/org/apache/qpid/test/unit/message/StreamMessageTest.java
+++ b/java/client/src/test/java/org/apache/qpid/test/unit/message/StreamMessageTest.java
@@ -1,11 +1,23 @@
-/**
- * User: Robert Greig
- * Date: 12-Dec-2006
- ******************************************************************************
- * (c) Copyright JP Morgan Chase Ltd 2006. All rights reserved. No part of
- * this program may be photocopied reproduced or translated to another
- * program language without prior written consent of JP Morgan Chase Ltd
- ******************************************************************************/
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
package org.apache.qpid.test.unit.message;
import junit.framework.TestCase;
@@ -47,7 +59,7 @@ public class StreamMessageTest extends TestCase
public void testStreamMessageEOF() throws Exception
{
- Connection con = new AMQConnection("vm://:1", "guest", "guest", "consumer1", "/test");
+ Connection con = new AMQConnection("vm://:1", "guest", "guest", "consumer1", "test");
AMQSession consumerSession = (AMQSession) con.createSession(false, Session.CLIENT_ACKNOWLEDGE);
@@ -60,7 +72,7 @@ public class StreamMessageTest extends TestCase
//force synch to ensure the consumer has resulted in a bound queue
((AMQSession) consumerSession).declareExchangeSynch(ExchangeDefaults.HEADERS_EXCHANGE_NAME, ExchangeDefaults.HEADERS_EXCHANGE_CLASS);
- Connection con2 = new AMQConnection("vm://:1", "guest", "guest", "producer1", "/test");
+ Connection con2 = new AMQConnection("vm://:1", "guest", "guest", "producer1", "test");
AMQSession producerSession = (AMQSession) con2.createSession(false, Session.CLIENT_ACKNOWLEDGE);
@@ -101,7 +113,7 @@ public class StreamMessageTest extends TestCase
public void testModifyReceivedMessageExpandsBuffer() throws Exception
{
- Connection con = new AMQConnection("vm://:1", "guest", "guest", "consumer1", "/test");
+ Connection con = new AMQConnection("vm://:1", "guest", "guest", "consumer1", "test");
AMQSession consumerSession = (AMQSession) con.createSession(false, Session.CLIENT_ACKNOWLEDGE);
AMQQueue queue = new AMQQueue("testQ");
MessageConsumer consumer = consumerSession.createConsumer(queue);
@@ -123,7 +135,7 @@ public class StreamMessageTest extends TestCase
}
}
});
- Connection con2 = new AMQConnection("vm://:1", "guest", "guest", "producer1", "/test");
+ Connection con2 = new AMQConnection("vm://:1", "guest", "guest", "producer1", "test");
AMQSession producerSession = (AMQSession) con2.createSession(false, Session.CLIENT_ACKNOWLEDGE);
MessageProducer mandatoryProducer = producerSession.createProducer(queue);
con.start();
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/topic/DurableSubscriptionTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/topic/DurableSubscriptionTest.java
index 5ded8aaeef..7e645f1a26 100644
--- a/java/client/src/test/java/org/apache/qpid/test/unit/topic/DurableSubscriptionTest.java
+++ b/java/client/src/test/java/org/apache/qpid/test/unit/topic/DurableSubscriptionTest.java
@@ -25,7 +25,7 @@ import org.apache.qpid.url.URLSyntaxException;
import org.apache.qpid.client.AMQConnection;
import org.apache.qpid.client.AMQSession;
import org.apache.qpid.client.AMQTopic;
-import org.apache.qpid.testutil.VMBrokerSetup;
+import org.apache.qpid.client.transport.TransportConnection;
import javax.jms.JMSException;
import javax.jms.Message;
@@ -39,10 +39,23 @@ import junit.framework.TestCase;
public class DurableSubscriptionTest extends TestCase
{
+
+ protected void setUp() throws Exception
+ {
+ super.setUp();
+ TransportConnection.createVMBroker(1);
+ }
+
+ protected void tearDown() throws Exception
+ {
+ super.tearDown();
+ TransportConnection.killAllVMBrokers();
+ }
+
public void testUnsubscribe() throws AMQException, JMSException, URLSyntaxException
{
AMQTopic topic = new AMQTopic("MyTopic");
- AMQConnection con = new AMQConnection("vm://:1", "guest", "guest", "test", "/test");
+ AMQConnection con = new AMQConnection("vm://:1", "guest", "guest", "test", "test");
Session session1 = con.createSession(false, AMQSession.NO_ACKNOWLEDGE);
MessageConsumer consumer1 = session1.createConsumer(topic);
MessageProducer producer = session1.createProducer(topic);
@@ -83,7 +96,7 @@ public class DurableSubscriptionTest extends TestCase
public void testDurability() throws AMQException, JMSException, URLSyntaxException
{
AMQTopic topic = new AMQTopic("MyTopic");
- AMQConnection con = new AMQConnection("vm://:1", "guest", "guest", "test", "/test");
+ AMQConnection con = new AMQConnection("vm://:1", "guest", "guest", "test", "test");
Session session1 = con.createSession(false, AMQSession.NO_ACKNOWLEDGE);
MessageConsumer consumer1 = session1.createConsumer(topic);
MessageProducer producer = session1.createProducer(topic);
@@ -128,6 +141,6 @@ public class DurableSubscriptionTest extends TestCase
public static junit.framework.Test suite()
{
- return new VMBrokerSetup(new junit.framework.TestSuite(DurableSubscriptionTest.class));
+ return new junit.framework.TestSuite(DurableSubscriptionTest.class);
}
}
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/topic/TopicPublisherTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/topic/TopicPublisherTest.java
index 4ffb3e8459..c4acf15a58 100644
--- a/java/client/src/test/java/org/apache/qpid/test/unit/topic/TopicPublisherTest.java
+++ b/java/client/src/test/java/org/apache/qpid/test/unit/topic/TopicPublisherTest.java
@@ -48,7 +48,7 @@ public class TopicPublisherTest extends TestCase
public void testUnidentifiedProducer() throws Exception
{
AMQTopic topic = new AMQTopic("MyTopic");
- AMQConnection con = new AMQConnection("vm://:1", "guest", "guest", "test", "/test");
+ AMQConnection con = new AMQConnection("vm://:1", "guest", "guest", "test", "test");
TopicSession session1 = con.createTopicSession(false, AMQSession.NO_ACKNOWLEDGE);
TopicPublisher publisher = session1.createPublisher(null);
MessageConsumer consumer1 = session1.createConsumer(topic);
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/topic/TopicSessionTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/topic/TopicSessionTest.java
index 794316d2f5..8e883a2184 100644
--- a/java/client/src/test/java/org/apache/qpid/test/unit/topic/TopicSessionTest.java
+++ b/java/client/src/test/java/org/apache/qpid/test/unit/topic/TopicSessionTest.java
@@ -51,7 +51,7 @@ public class TopicSessionTest extends TestCase
public void testTopicSubscriptionUnsubscription() throws Exception
{
AMQTopic topic = new AMQTopic("MyTopic");
- AMQConnection con = new AMQConnection("vm://:1?retries='0'", "guest", "guest", "test", "/test");
+ AMQConnection con = new AMQConnection("vm://:1?retries='0'", "guest", "guest", "test", "test");
TopicSession session1 = con.createTopicSession(false, AMQSession.NO_ACKNOWLEDGE);
TopicSubscriber sub = session1.createDurableSubscriber(topic,"subscription0");
TopicPublisher publisher = session1.createPublisher(topic);
@@ -97,7 +97,7 @@ public class TopicSessionTest extends TestCase
{
AMQTopic topic = new AMQTopic("MyTopic1" + String.valueOf(shutdown));
AMQTopic topic2 = new AMQTopic("MyOtherTopic1" + String.valueOf(shutdown));
- AMQConnection con = new AMQConnection("vm://:1?retries='0'", "guest", "guest", "test", "/test");
+ AMQConnection con = new AMQConnection("vm://:1?retries='0'", "guest", "guest", "test", "test");
TopicSession session1 = con.createTopicSession(false, AMQSession.NO_ACKNOWLEDGE);
TopicSubscriber sub = session1.createDurableSubscriber(topic, "subscription0");
TopicPublisher publisher = session1.createPublisher(null);
@@ -112,7 +112,7 @@ public class TopicSessionTest extends TestCase
{
session1.close();
con.close();
- con = new AMQConnection("vm://:1?retries='0'", "guest", "guest", "test", "/test");
+ con = new AMQConnection("vm://:1?retries='0'", "guest", "guest", "test", "test");
con.start();
session1 = con.createTopicSession(false, AMQSession.NO_ACKNOWLEDGE);
publisher = session1.createPublisher(null);
@@ -134,11 +134,11 @@ public class TopicSessionTest extends TestCase
public void testUnsubscriptionAfterConnectionClose() throws Exception
{
AMQTopic topic = new AMQTopic("MyTopic3");
- AMQConnection con1 = new AMQConnection("vm://:1?retries='0'", "guest", "guest", "test", "/test");
+ AMQConnection con1 = new AMQConnection("vm://:1?retries='0'", "guest", "guest", "test", "test");
TopicSession session1 = con1.createTopicSession(false, AMQSession.NO_ACKNOWLEDGE);
TopicPublisher publisher = session1.createPublisher(topic);
- AMQConnection con2 = new AMQConnection("vm://:1?retries='0'", "guest", "guest", "test2", "/test");
+ AMQConnection con2 = new AMQConnection("vm://:1?retries='0'", "guest", "guest", "test2", "test");
TopicSession session2 = con2.createTopicSession(false, AMQSession.NO_ACKNOWLEDGE);
TopicSubscriber sub = session2.createDurableSubscriber(topic, "subscription0");
@@ -149,7 +149,7 @@ public class TopicSessionTest extends TestCase
assertNotNull(tm);
con2.close();
publisher.publish(session1.createTextMessage("Hello2"));
- con2 = new AMQConnection("vm://:1?retries='0'", "guest", "guest", "test2", "/test");
+ con2 = new AMQConnection("vm://:1?retries='0'", "guest", "guest", "test2", "test");
session2 = con2.createTopicSession(false, AMQSession.NO_ACKNOWLEDGE);
sub = session2.createDurableSubscriber(topic, "subscription0");
con2.start();
@@ -163,14 +163,14 @@ public class TopicSessionTest extends TestCase
public void testTextMessageCreation() throws Exception
{
AMQTopic topic = new AMQTopic("MyTopic4");
- AMQConnection con = new AMQConnection("vm://:1?retries='0'", "guest", "guest", "test", "/test");
+ AMQConnection con = new AMQConnection("vm://:1?retries='0'", "guest", "guest", "test", "test");
TopicSession session1 = con.createTopicSession(false, AMQSession.NO_ACKNOWLEDGE);
TopicPublisher publisher = session1.createPublisher(topic);
MessageConsumer consumer1 = session1.createConsumer(topic);
con.start();
TextMessage tm = session1.createTextMessage("Hello");
publisher.publish(tm);
- tm = (TextMessage) consumer1.receive(2000);
+ tm = (TextMessage) consumer1.receive(200000L);
assertNotNull(tm);
String msgText = tm.getText();
assertEquals("Hello", msgText);
@@ -178,7 +178,7 @@ public class TopicSessionTest extends TestCase
msgText = tm.getText();
assertNull(msgText);
publisher.publish(tm);
- tm = (TextMessage) consumer1.receive(2000);
+ tm = (TextMessage) consumer1.receive(20000000L);
assertNotNull(tm);
msgText = tm.getText();
assertNull(msgText);
@@ -202,7 +202,7 @@ public class TopicSessionTest extends TestCase
public void testSendingSameMessage() throws Exception
{
- AMQConnection conn = new AMQConnection("vm://:1?retries='0'", "guest", "guest", "test", "/test");
+ AMQConnection conn = new AMQConnection("vm://:1?retries='0'", "guest", "guest", "test", "test");
TopicSession session = conn.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
TemporaryTopic topic = session.createTemporaryTopic();
assertNotNull(topic);
@@ -219,12 +219,13 @@ public class TopicSessionTest extends TestCase
assertNotNull(receivedMessage);
assertEquals(sentMessage.getText(),receivedMessage.getText());
+ conn.close();
}
public void testTemporaryTopic() throws Exception
{
- AMQConnection conn = new AMQConnection("vm://:1?retries='0'", "guest", "guest", "test", "/test");
+ AMQConnection conn = new AMQConnection("vm://:1?retries='0'", "guest", "guest", "test", "test");
TopicSession session = conn.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
TemporaryTopic topic = session.createTemporaryTopic();
assertNotNull(topic);
diff --git a/java/client/src/test/java/org/apache/qpid/test/unit/transacted/TransactedTest.java b/java/client/src/test/java/org/apache/qpid/test/unit/transacted/TransactedTest.java
index 3e1fc04626..ce6df83baf 100644
--- a/java/client/src/test/java/org/apache/qpid/test/unit/transacted/TransactedTest.java
+++ b/java/client/src/test/java/org/apache/qpid/test/unit/transacted/TransactedTest.java
@@ -23,8 +23,11 @@ package org.apache.qpid.test.unit.transacted;
import org.apache.qpid.client.AMQConnection;
import org.apache.qpid.client.AMQQueue;
import org.apache.qpid.client.AMQSession;
+import org.apache.qpid.client.transport.TransportConnection;
import org.apache.qpid.testutil.VMBrokerSetup;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.exchange.ExchangeDefaults;
+import org.apache.mina.util.SessionLog;
import org.apache.log4j.Logger;
import javax.jms.*;
@@ -54,10 +57,11 @@ public class TransactedTest extends TestCase
protected void setUp() throws Exception
{
super.setUp();
- queue1 = new AMQQueue("Q1", "Q1", false, true);
+ TransportConnection.createVMBroker(1);
+ queue1 = new AMQQueue(new AMQShortString("Q1"), new AMQShortString("Q1"), false, true);
queue2 = new AMQQueue("Q2", false);
- con = new AMQConnection("vm://:1", "guest", "guest", "TransactedTest", "/test");
+ con = new AMQConnection("vm://:1", "guest", "guest", "TransactedTest", "test");
session = con.createSession(true, 0);
consumer1 = session.createConsumer(queue1);
//Dummy just to create the queue.
@@ -66,16 +70,26 @@ public class TransactedTest extends TestCase
producer2 = session.createProducer(queue2);
con.start();
- prepCon = new AMQConnection("vm://:1", "guest", "guest", "PrepConnection", "/test");
+ prepCon = new AMQConnection("vm://:1", "guest", "guest", "PrepConnection", "test");
prepSession = prepCon.createSession(false, AMQSession.NO_ACKNOWLEDGE);
prepProducer1 = prepSession.createProducer(queue1);
prepCon.start();
+
+// //add some messages
+// prepProducer1.send(prepSession.createTextMessage("A"));
+// prepProducer1.send(prepSession.createTextMessage("B"));
+// prepProducer1.send(prepSession.createTextMessage("C"));
+//
+// testCon = new AMQConnection("vm://:1", "guest", "guest", "TestConnection", "/test");
+// testSession = testCon.createSession(false, AMQSession.NO_ACKNOWLEDGE);
+// testConsumer2 = testSession.createConsumer(queue2);
}
protected void tearDown() throws Exception
{
con.close();
prepCon.close();
+ TransportConnection.killAllVMBrokers();
super.tearDown();
}
@@ -96,9 +110,9 @@ public class TransactedTest extends TestCase
//commit
session.commit();
-
+ testCon.start();
//ensure sent messages can be received and received messages are gone
- testCon = new AMQConnection("vm://:1", "guest", "guest", "TestConnection", "/test");
+ testCon = new AMQConnection("vm://:1", "guest", "guest", "TestConnection", "test");
testSession = testCon.createSession(false, AMQSession.NO_ACKNOWLEDGE);
testConsumer1 = testSession.createConsumer(queue1);
testConsumer2 = testSession.createConsumer(queue2);
@@ -108,6 +122,7 @@ public class TransactedTest extends TestCase
expect("Y", testConsumer2.receive(1000));
expect("Z", testConsumer2.receive(1000));
+ testConsumer1 = testSession.createConsumer(queue1);
assertTrue(null == testConsumer1.receive(1000));
assertTrue(null == testConsumer2.receive(1000));
testCon.close();
@@ -141,11 +156,12 @@ public class TransactedTest extends TestCase
expect("A", consumer1.receive(1000));
expect("B", consumer1.receive(1000));
expect("C", consumer1.receive(1000));
-
+ testCon.start();
+ testConsumer1 = testSession.createConsumer(queue1);
//commit
session.commit();
- testCon = new AMQConnection("vm://:1", "guest", "guest", "TestConnection", "/test");
+ testCon = new AMQConnection("vm://:1", "guest", "guest", "TestConnection", "test");
testSession = testCon.createSession(false, AMQSession.NO_ACKNOWLEDGE);
testConsumer1 = testSession.createConsumer(queue1);
testConsumer2 = testSession.createConsumer(queue2);
@@ -164,7 +180,7 @@ public class TransactedTest extends TestCase
public void testResendsMsgsAfterSessionClose() throws Exception
{
- Connection con = new AMQConnection("vm://:1", "guest", "guest", "consumer1", "/test");
+ Connection con = new AMQConnection("vm://:1", "guest", "guest", "consumer1", "test");
Session consumerSession = con.createSession(true, Session.CLIENT_ACKNOWLEDGE);
AMQQueue queue3 = new AMQQueue("Q3", false);
@@ -172,7 +188,7 @@ public class TransactedTest extends TestCase
//force synch to ensure the consumer has resulted in a bound queue
((AMQSession) consumerSession).declareExchangeSynch(ExchangeDefaults.DIRECT_EXCHANGE_NAME, ExchangeDefaults.DIRECT_EXCHANGE_CLASS);
- Connection con2 = new AMQConnection("vm://:1", "guest", "guest", "producer1", "/test");
+ Connection con2 = new AMQConnection("vm://:1", "guest", "guest", "producer1", "test");
Session producerSession = con2.createSession(true, Session.CLIENT_ACKNOWLEDGE);
MessageProducer producer = producerSession.createProducer(queue3);
@@ -234,6 +250,7 @@ public class TransactedTest extends TestCase
con.close();
con2.close();
+
}
// This checks that queue Q1 is in fact empty and does not have any stray
@@ -251,6 +268,6 @@ public class TransactedTest extends TestCase
public static junit.framework.Test suite()
{
- return new VMBrokerSetup(new junit.framework.TestSuite(TransactedTest.class));
+ return new junit.framework.TestSuite(TransactedTest.class);
}
}
diff --git a/java/cluster/src/main/java/org/apache/qpid/server/cluster/ClientHandlerRegistry.java b/java/cluster/src/main/java/org/apache/qpid/server/cluster/ClientHandlerRegistry.java
index 7d9a50e354..c79548a4ec 100644
--- a/java/cluster/src/main/java/org/apache/qpid/server/cluster/ClientHandlerRegistry.java
+++ b/java/cluster/src/main/java/org/apache/qpid/server/cluster/ClientHandlerRegistry.java
@@ -32,6 +32,7 @@ import org.apache.qpid.client.state.StateAwareMethodListener;
import org.apache.qpid.client.protocol.AMQProtocolSession;
import org.apache.qpid.framing.AMQFrame;
import org.apache.qpid.framing.AMQMethodBody;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.framing.ConnectionCloseBody;
import org.apache.qpid.framing.ConnectionOpenOkBody;
import org.apache.qpid.framing.ConnectionSecureBody;
@@ -128,9 +129,9 @@ public class ClientHandlerRegistry extends AMQStateManager
class ConnectionTuneHandler extends ConnectionTuneMethodHandler
{
- protected AMQMethodBody createConnectionOpenMethodBody(String path, String capabilities, boolean insist)
+ protected AMQMethodBody createConnectionOpenMethodBody(AMQProtocolSession protocolSession, AMQShortString path, AMQShortString capabilities, boolean insist)
{
- return super.createConnectionOpenMethodBody(path, ClusterCapability.add(capabilities, _identity), insist);
+ return super.createConnectionOpenMethodBody(protocolSession, path, new AMQShortString(ClusterCapability.add(capabilities, _identity)), insist);
}
}
}
diff --git a/java/cluster/src/main/java/org/apache/qpid/server/cluster/ClusterBuilder.java b/java/cluster/src/main/java/org/apache/qpid/server/cluster/ClusterBuilder.java
index 89dcfc080f..d95e90283f 100644
--- a/java/cluster/src/main/java/org/apache/qpid/server/cluster/ClusterBuilder.java
+++ b/java/cluster/src/main/java/org/apache/qpid/server/cluster/ClusterBuilder.java
@@ -46,8 +46,8 @@ class ClusterBuilder
ServerHandlerRegistry getHandlerRegistry()
{
- // TODO - FIX THIS!
- return new ServerHandlerRegistry(getHandlerFactory(), null, null, null);
+ // TODO - FIX THIS! These cannot be null to work correctly
+ return new ServerHandlerRegistry(getHandlerFactory(), null, null);
}
private MethodHandlerFactory getHandlerFactory()
diff --git a/java/cluster/src/main/java/org/apache/qpid/server/cluster/ClusterCapability.java b/java/cluster/src/main/java/org/apache/qpid/server/cluster/ClusterCapability.java
index 0411019334..57c48f0611 100644
--- a/java/cluster/src/main/java/org/apache/qpid/server/cluster/ClusterCapability.java
+++ b/java/cluster/src/main/java/org/apache/qpid/server/cluster/ClusterCapability.java
@@ -20,6 +20,8 @@
*/
package org.apache.qpid.server.cluster;
+import org.apache.qpid.framing.AMQShortString;
+
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -28,22 +30,22 @@ public class ClusterCapability
public static final String PATTERN = ".*\\bcluster_peer=(\\S*:\\d*)\b*.*";
public static final String PEER = "cluster_peer";
- public static String add(String original, MemberHandle identity)
+ public static AMQShortString add(AMQShortString original, MemberHandle identity)
{
- return original == null ? peer(identity) : original + " " + peer(identity);
+ return original == null ? peer(identity) : new AMQShortString(original + " " + peer(identity));
}
- private static String peer(MemberHandle identity)
+ private static AMQShortString peer(MemberHandle identity)
{
- return PEER + "=" + identity.getDetails();
+ return new AMQShortString(PEER + "=" + identity.getDetails());
}
- public static boolean contains(String in)
+ public static boolean contains(AMQShortString in)
{
- return in != null && in.contains(in);
+ return in != null; // && in.contains(in);
}
- public static MemberHandle getPeer(String in)
+ public static MemberHandle getPeer(AMQShortString in)
{
Matcher matcher = Pattern.compile(PATTERN).matcher(in);
if (matcher.matches())
diff --git a/java/cluster/src/main/java/org/apache/qpid/server/cluster/ClusteredProtocolHandler.java b/java/cluster/src/main/java/org/apache/qpid/server/cluster/ClusteredProtocolHandler.java
index c1306b4c13..ee5aa48db9 100644
--- a/java/cluster/src/main/java/org/apache/qpid/server/cluster/ClusteredProtocolHandler.java
+++ b/java/cluster/src/main/java/org/apache/qpid/server/cluster/ClusteredProtocolHandler.java
@@ -38,6 +38,7 @@ import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.registry.ApplicationRegistry;
import org.apache.qpid.server.registry.IApplicationRegistry;
import org.apache.qpid.server.cluster.util.LogMessage;
+import org.apache.qpid.server.virtualhost.VirtualHostRegistry;
import java.net.InetSocketAddress;
@@ -55,13 +56,8 @@ public class ClusteredProtocolHandler extends AMQPFastProtocolHandler implements
}
public ClusteredProtocolHandler(IApplicationRegistry registry, InetSocketAddress address)
- {
- this(registry.getQueueRegistry(), registry.getExchangeRegistry(), address);
- }
-
- public ClusteredProtocolHandler(QueueRegistry queueRegistry, ExchangeRegistry exchangeRegistry, InetSocketAddress address)
- {
- super(queueRegistry, exchangeRegistry);
+ {
+ super(registry);
ClusterBuilder builder = new ClusterBuilder(address);
_groupMgr = builder.getGroupManager();
_handlers = builder.getHandlerRegistry();
@@ -74,9 +70,9 @@ public class ClusteredProtocolHandler extends AMQPFastProtocolHandler implements
_handlers = handler._handlers;
}
- protected void createSession(IoSession session, QueueRegistry queues, ExchangeRegistry exchanges, AMQProtocolSession protocolSession, AMQCodecFactory codec) throws AMQException
+ protected void createSession(IoSession session, VirtualHostRegistry virtualHostRegistry, AMQProtocolSession protocolSession, AMQCodecFactory codec) throws AMQException
{
- new ClusteredProtocolSession(session, queues, exchanges, codec, new ServerHandlerRegistry(_handlers, queues, exchanges, protocolSession));
+ new ClusteredProtocolSession(session, virtualHostRegistry, codec, new ServerHandlerRegistry(_handlers, virtualHostRegistry, protocolSession));
}
void connect(String join) throws Exception
@@ -176,12 +172,12 @@ public class ClusteredProtocolHandler extends AMQPFastProtocolHandler implements
private boolean isMembershipAnnouncement(Object msg)
{
- return msg instanceof AMQFrame && (((AMQFrame) msg).bodyFrame instanceof ClusterMembershipBody);
+ return msg instanceof AMQFrame && (((AMQFrame) msg).getBodyFrame() instanceof ClusterMembershipBody);
}
private boolean isBufferable(Object msg)
{
- return msg instanceof AMQFrame && isBuffereable(((AMQFrame) msg).bodyFrame);
+ return msg instanceof AMQFrame && isBuffereable(((AMQFrame) msg).getBodyFrame());
}
private boolean isBuffereable(AMQBody body)
diff --git a/java/cluster/src/main/java/org/apache/qpid/server/cluster/ClusteredProtocolSession.java b/java/cluster/src/main/java/org/apache/qpid/server/cluster/ClusteredProtocolSession.java
index e2b388e174..dc849ddc76 100644
--- a/java/cluster/src/main/java/org/apache/qpid/server/cluster/ClusteredProtocolSession.java
+++ b/java/cluster/src/main/java/org/apache/qpid/server/cluster/ClusteredProtocolSession.java
@@ -24,7 +24,10 @@ import org.apache.mina.common.IoSession;
import org.apache.qpid.AMQException;
import org.apache.qpid.codec.AMQCodecFactory;
import org.apache.qpid.server.AMQChannel;
+import org.apache.qpid.server.virtualhost.VirtualHostRegistry;
+import org.apache.qpid.server.virtualhost.VirtualHost;
import org.apache.qpid.server.exchange.ExchangeRegistry;
+import org.apache.qpid.server.exchange.MessageRouter;
import org.apache.qpid.server.protocol.AMQMinaProtocolSession;
import org.apache.qpid.server.protocol.AMQProtocolSession;
import org.apache.qpid.server.queue.AMQMessage;
@@ -32,6 +35,7 @@ import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.registry.ApplicationRegistry;
import org.apache.qpid.server.registry.IApplicationRegistry;
import org.apache.qpid.server.state.AMQStateManager;
+import org.apache.qpid.server.store.MessageStore;
import org.apache.qpid.protocol.AMQMethodListener;
import org.apache.qpid.protocol.AMQProtocolWriter;
@@ -39,10 +43,12 @@ public class ClusteredProtocolSession extends AMQMinaProtocolSession
{
private MemberHandle _peer;
- public ClusteredProtocolSession(IoSession session, QueueRegistry queueRegistry, ExchangeRegistry exchangeRegistry, AMQCodecFactory codecFactory, AMQStateManager stateManager)
- throws AMQException
+ public ClusteredProtocolSession(IoSession session, VirtualHostRegistry virtualHostRegistry, AMQCodecFactory codecFactory, AMQStateManager stateManager) throws AMQException
+// public ClusteredProtocolSession(IoSession session, QueueRegistry queueRegistry,
+// ExchangeRegistry exchangeRegistry, AMQCodecFactory codecFactory) throws AMQException
{
- super(session, queueRegistry, exchangeRegistry, codecFactory, stateManager);
+ super(session, virtualHostRegistry, codecFactory, stateManager);
+// super(session, queueRegistry, exchangeRegistry, codecFactory);
}
public boolean isPeerSession()
@@ -65,7 +71,8 @@ public class ClusteredProtocolSession extends AMQMinaProtocolSession
AMQChannel channel = super.getChannel(channelId);
if (isPeerSession() && channel == null)
{
- channel = new OneUseChannel(channelId, this, getStateManager());
+ VirtualHost virtualHost = getVirtualHost();
+ channel = new OneUseChannel(channelId, this, virtualHost.getMessageStore(),virtualHost.getExchangeRegistry(), getStateManager());
addChannel(channel);
}
return channel;
@@ -101,19 +108,12 @@ public class ClusteredProtocolSession extends AMQMinaProtocolSession
*/
private class OneUseChannel extends AMQChannel
{
- public OneUseChannel(int channelId, AMQProtocolSession session,
- AMQMethodListener methodListener)
- {
- this(channelId, session, ApplicationRegistry.getInstance(), methodListener);
- }
-
- public OneUseChannel(int channelId, AMQProtocolSession session, IApplicationRegistry registry,
- AMQMethodListener methodListener)
+ public OneUseChannel(int channelId, AMQProtocolSession session, MessageStore messageStore, MessageRouter exchanges, AMQMethodListener methodListener)
{
super(channelId,
session,
- registry.getMessageStore(),
- registry.getExchangeRegistry(),
+ messageStore,
+ exchanges,
methodListener);
}
diff --git a/java/cluster/src/main/java/org/apache/qpid/server/cluster/DefaultGroupManager.java b/java/cluster/src/main/java/org/apache/qpid/server/cluster/DefaultGroupManager.java
index b72e95b35e..29459e29a8 100644
--- a/java/cluster/src/main/java/org/apache/qpid/server/cluster/DefaultGroupManager.java
+++ b/java/cluster/src/main/java/org/apache/qpid/server/cluster/DefaultGroupManager.java
@@ -22,16 +22,10 @@ package org.apache.qpid.server.cluster;
import org.apache.log4j.Logger;
import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.ClusterJoinBody;
-import org.apache.qpid.framing.ClusterLeaveBody;
-import org.apache.qpid.framing.ClusterMembershipBody;
-import org.apache.qpid.framing.ClusterPingBody;
-import org.apache.qpid.framing.ClusterSuspectBody;
-import org.apache.qpid.framing.AMQMethodBody;
+import org.apache.qpid.framing.*;
import org.apache.qpid.server.cluster.policy.StandardPolicies;
import org.apache.qpid.server.cluster.replay.ReplayManager;
import org.apache.qpid.server.cluster.util.LogMessage;
-import org.apache.qpid.server.cluster.util.InvokeMultiple;
import java.util.List;
@@ -96,7 +90,7 @@ public class DefaultGroupManager implements GroupManager, MemberFailureListener,
Broker destination = findBroker(broker);
if(destination == null)
{
- _logger.warn(new LogMessage("Invalid destination sending {0}. {1} not known", message, broker));
+ _logger.warn(new LogMessage("Invalid destination sending {0}. {1} not known", message, broker));
}
else
{
@@ -114,12 +108,15 @@ public class DefaultGroupManager implements GroupManager, MemberFailureListener,
{
// AMQP version change: Hardwire the version to 0-9 (major=0, minor=9)
// TODO: Connect this to the session version obtained from ProtocolInitiation for this session.
- ClusterPingBody ping = new ClusterPingBody((byte)0, (byte)9);
- ping.broker = _group.getLocal().getDetails();
- ping.responseRequired = true;
- ping.load = _loadTable.getLocalLoad();
+ ClusterPingBody ping = new ClusterPingBody((byte)0,
+ (byte)9,
+ ClusterPingBody.getClazz((byte)0, (byte)9),
+ ClusterPingBody.getMethod((byte)0, (byte)9),
+ _group.getLocal().getDetails(),
+ _loadTable.getLocalLoad(),
+ true);
BlockingHandler handler = new BlockingHandler();
- send(getLeader(), new SimpleSendable(ping), handler);
+ send(getLeader(), new SimpleBodySendable(ping), handler);
handler.waitForCompletion();
if (handler.failed())
{
@@ -162,9 +159,13 @@ public class DefaultGroupManager implements GroupManager, MemberFailureListener,
_logger.info(new LogMessage("Connected to {0}. joining", leader));
// AMQP version change: Hardwire the version to 0-9 (major=0, minor=9)
// TODO: Connect this to the session version obtained from ProtocolInitiation for this session.
- ClusterJoinBody join = new ClusterJoinBody((byte)0, (byte)9);
- join.broker = _group.getLocal().getDetails();
- send(leader, new SimpleSendable(join));
+ ClusterJoinBody join = new ClusterJoinBody((byte)0,
+ (byte)9,
+ ClusterJoinBody.getClazz((byte)0, (byte)9),
+ ClusterJoinBody.getMethod((byte)0, (byte)9),
+ _group.getLocal().getDetails());
+
+ send(leader, new SimpleBodySendable(join));
}
private Broker connectToLeader(MemberHandle member) throws AMQException
@@ -183,9 +184,13 @@ public class DefaultGroupManager implements GroupManager, MemberFailureListener,
{
// AMQP version change: Hardwire the version to 0-9 (major=0, minor=9)
// TODO: Connect this to the session version obtained from ProtocolInitiation for this session.
- ClusterLeaveBody leave = new ClusterLeaveBody((byte)0, (byte)9);
- leave.broker = _group.getLocal().getDetails();
- send(getLeader(), new SimpleSendable(leave));
+ ClusterLeaveBody leave = new ClusterLeaveBody((byte)0,
+ (byte)9,
+ ClusterLeaveBody.getClazz((byte)0, (byte)9),
+ ClusterLeaveBody.getMethod((byte)0, (byte)9),
+ _group.getLocal().getDetails());
+
+ send(getLeader(), new SimpleBodySendable(leave));
}
private void suspect(MemberHandle broker) throws AMQException
@@ -206,9 +211,13 @@ public class DefaultGroupManager implements GroupManager, MemberFailureListener,
{
// AMQP version change: Hardwire the version to 0-9 (major=0, minor=9)
// TODO: Connect this to the session version obtained from ProtocolInitiation for this session.
- ClusterSuspectBody suspect = new ClusterSuspectBody((byte)0, (byte)9);
- suspect.broker = broker.getDetails();
- send(getLeader(), new SimpleSendable(suspect));
+ ClusterSuspectBody suspect = new ClusterSuspectBody((byte)0,
+ (byte)9,
+ ClusterSuspectBody.getClazz((byte)0, (byte)9),
+ ClusterSuspectBody.getMethod((byte)0, (byte)9),
+ broker.getDetails());
+
+ send(getLeader(), new SimpleBodySendable(suspect));
}
}
@@ -230,10 +239,13 @@ public class DefaultGroupManager implements GroupManager, MemberFailureListener,
//pass request on to leader:
// AMQP version change: Hardwire the version to 0-9 (major=0, minor=9)
// TODO: Connect this to the session version obtained from ProtocolInitiation for this session.
- ClusterJoinBody request = new ClusterJoinBody((byte)0, (byte)9);
- request.broker = member.getDetails();
+ ClusterJoinBody request = new ClusterJoinBody((byte)0, (byte)9,
+ ClusterJoinBody.getClazz((byte)0, (byte)9),
+ ClusterJoinBody.getMethod((byte)0, (byte)9),
+ member.getDetails());
+
Broker leader = getLeader();
- send(leader, new SimpleSendable(request));
+ send(leader, new SimpleBodySendable(request));
_logger.info(new LogMessage("Passed join request for {0} to {1}", member, leader));
}
}
@@ -277,9 +289,12 @@ public class DefaultGroupManager implements GroupManager, MemberFailureListener,
{
// AMQP version change: Hardwire the version to 0-9 (major=0, minor=9)
// TODO: Connect this to the session version obtained from ProtocolInitiation for this session.
- ClusterMembershipBody announce = new ClusterMembershipBody((byte)0, (byte)9);
- //TODO: revise this way of converting String to bytes...
- announce.members = membership.getBytes();
+ ClusterMembershipBody announce = new ClusterMembershipBody((byte)0, (byte)9,
+ ClusterMembershipBody.getClazz((byte)0, (byte)9),
+ ClusterMembershipBody.getMethod((byte)0, (byte)9),
+ membership.getBytes());
+
+
return announce;
}
@@ -287,7 +302,7 @@ public class DefaultGroupManager implements GroupManager, MemberFailureListener,
{
String membership = SimpleMemberHandle.membersToString(_group.getMembers());
ClusterMembershipBody announce = createAnnouncement(membership);
- broadcast(new SimpleSendable(announce));
+ broadcast(new SimpleBodySendable(announce));
_logger.info(new LogMessage("Membership announcement sent: {0}", membership));
}
diff --git a/java/cluster/src/main/java/org/apache/qpid/server/cluster/Main.java b/java/cluster/src/main/java/org/apache/qpid/server/cluster/Main.java
index 3eeddd7b4e..5746a32c26 100644
--- a/java/cluster/src/main/java/org/apache/qpid/server/cluster/Main.java
+++ b/java/cluster/src/main/java/org/apache/qpid/server/cluster/Main.java
@@ -83,7 +83,7 @@ public class Main extends org.apache.qpid.server.Main
// implementation provided by MINA
if (connectorConfig.enableExecutorPool)
{
- sconfig.setThreadModel(new ReadWriteThreadModel());
+ sconfig.setThreadModel(ReadWriteThreadModel.getInstance());
}
String host = InetAddress.getLocalHost().getHostName();
diff --git a/java/cluster/src/main/java/org/apache/qpid/server/cluster/MemberHandle.java b/java/cluster/src/main/java/org/apache/qpid/server/cluster/MemberHandle.java
index b14fede5aa..b8099a12f7 100644
--- a/java/cluster/src/main/java/org/apache/qpid/server/cluster/MemberHandle.java
+++ b/java/cluster/src/main/java/org/apache/qpid/server/cluster/MemberHandle.java
@@ -20,6 +20,8 @@
*/
package org.apache.qpid.server.cluster;
+import org.apache.qpid.framing.AMQShortString;
+
public interface MemberHandle
{
public String getHost();
@@ -30,5 +32,5 @@ public interface MemberHandle
public boolean matches(String host, int port);
- public String getDetails();
+ public AMQShortString getDetails();
}
diff --git a/java/cluster/src/main/java/org/apache/qpid/server/cluster/MinaBrokerProxy.java b/java/cluster/src/main/java/org/apache/qpid/server/cluster/MinaBrokerProxy.java
index 011ce6bafb..28656b98a4 100644
--- a/java/cluster/src/main/java/org/apache/qpid/server/cluster/MinaBrokerProxy.java
+++ b/java/cluster/src/main/java/org/apache/qpid/server/cluster/MinaBrokerProxy.java
@@ -65,7 +65,6 @@ public class MinaBrokerProxy extends Broker implements MethodHandler
{
super(host, port);
_local = local;
- // TODO - FIX THIS
_legacyHandler = new ClientHandlerRegistry(local, null);
}
@@ -183,7 +182,7 @@ public class MinaBrokerProxy extends Broker implements MethodHandler
{
//signal redirection to waiting thread
ConnectionRedirectBody redirect = (ConnectionRedirectBody) method;
- String[] parts = redirect.host.split(":");
+ String[] parts = redirect.host.toString().split(":");
_connectionMonitor.redirect(parts[0], Integer.parseInt(parts[1]));
}
else
@@ -203,15 +202,15 @@ public class MinaBrokerProxy extends Broker implements MethodHandler
private void handleFrame(AMQFrame frame) throws AMQException
{
- AMQBody body = frame.bodyFrame;
+ AMQBody body = frame.getBodyFrame();
if (body instanceof AMQRequestBody)
{
- handleMethod(frame.channel, ((AMQRequestBody)body).getMethodPayload(),
+ handleMethod(frame.getChannel(), ((AMQRequestBody)body).getMethodPayload(),
((AMQRequestBody)body).getRequestId());
}
else if (body instanceof AMQResponseBody)
{
- handleMethod(frame.channel, ((AMQResponseBody)body).getMethodPayload(),
+ handleMethod(frame.getChannel(), ((AMQResponseBody)body).getMethodPayload(),
((AMQRequestBody)body).getRequestId());
}
else
diff --git a/java/cluster/src/main/java/org/apache/qpid/server/cluster/ServerHandlerRegistry.java b/java/cluster/src/main/java/org/apache/qpid/server/cluster/ServerHandlerRegistry.java
index 27d5629f27..e0900d3fe4 100644
--- a/java/cluster/src/main/java/org/apache/qpid/server/cluster/ServerHandlerRegistry.java
+++ b/java/cluster/src/main/java/org/apache/qpid/server/cluster/ServerHandlerRegistry.java
@@ -28,8 +28,8 @@ import org.apache.qpid.server.state.IllegalStateTransitionException;
import org.apache.qpid.server.state.StateAwareMethodListener;
import org.apache.qpid.server.cluster.util.LogMessage;
import org.apache.qpid.server.queue.QueueRegistry;
-import org.apache.qpid.server.exchange.ExchangeRegistry;
import org.apache.qpid.server.protocol.AMQProtocolSession;
+import org.apache.qpid.server.virtualhost.VirtualHostRegistry;
import java.util.HashMap;
import java.util.Map;
@@ -43,23 +43,20 @@ class ServerHandlerRegistry extends AMQStateManager
private final Logger _logger = Logger.getLogger(ServerHandlerRegistry.class);
private final Map<AMQState, MethodHandlerRegistry> _handlers = new HashMap<AMQState, MethodHandlerRegistry>();
- ServerHandlerRegistry(QueueRegistry queueRegistry, ExchangeRegistry exchangeRegistry,
- AMQProtocolSession protocolSession)
+ ServerHandlerRegistry(VirtualHostRegistry virtualHostRegistry, AMQProtocolSession protocolSession)
{
- super(AMQState.CONNECTION_NOT_STARTED, false, queueRegistry, exchangeRegistry, protocolSession);
+ super(AMQState.CONNECTION_NOT_STARTED, false, virtualHostRegistry, protocolSession);
}
- ServerHandlerRegistry(ServerHandlerRegistry s, QueueRegistry queueRegistry,
- ExchangeRegistry exchangeRegistry, AMQProtocolSession protocolSession)
+ ServerHandlerRegistry(ServerHandlerRegistry s, VirtualHostRegistry virtualHostRegistry, AMQProtocolSession protocolSession)
{
- this(queueRegistry, exchangeRegistry, protocolSession);
+ this(virtualHostRegistry, protocolSession);
_handlers.putAll(s._handlers);
}
- ServerHandlerRegistry(MethodHandlerFactory factory, QueueRegistry queueRegistry,
- ExchangeRegistry exchangeRegistry, AMQProtocolSession protocolSession)
+ ServerHandlerRegistry(MethodHandlerFactory factory, VirtualHostRegistry virtualHostRegistry, AMQProtocolSession protocolSession)
{
- this(queueRegistry, exchangeRegistry, protocolSession);
+ this(virtualHostRegistry, protocolSession);
init(factory);
}
diff --git a/java/cluster/src/main/java/org/apache/qpid/server/cluster/SimpleBodySendable.java b/java/cluster/src/main/java/org/apache/qpid/server/cluster/SimpleBodySendable.java
new file mode 100644
index 0000000000..f7c40c60b3
--- /dev/null
+++ b/java/cluster/src/main/java/org/apache/qpid/server/cluster/SimpleBodySendable.java
@@ -0,0 +1,45 @@
+/*
+ *
+ * Copyright (c) 2006 The Apache Software Foundation
+ *
+ * Licensed 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.cluster;
+
+import org.apache.qpid.AMQException;
+import org.apache.qpid.framing.AMQBody;
+import org.apache.qpid.framing.AMQFrame;
+
+/**
+ */
+public class SimpleBodySendable implements Sendable
+{
+ private final AMQBody _body;
+
+ public SimpleBodySendable(AMQBody body)
+ {
+ _body = body;
+ }
+
+ public void send(int channel, Member member) throws AMQException
+ {
+ member.send(new AMQFrame(channel, _body));
+ }
+
+ public String toString()
+ {
+ return _body.toString();
+ }
+
+}
diff --git a/java/cluster/src/main/java/org/apache/qpid/server/cluster/SimpleMemberHandle.java b/java/cluster/src/main/java/org/apache/qpid/server/cluster/SimpleMemberHandle.java
index b6d5e3d88d..1255094b1d 100644
--- a/java/cluster/src/main/java/org/apache/qpid/server/cluster/SimpleMemberHandle.java
+++ b/java/cluster/src/main/java/org/apache/qpid/server/cluster/SimpleMemberHandle.java
@@ -20,6 +20,8 @@
*/
package org.apache.qpid.server.cluster;
+import org.apache.qpid.framing.AMQShortString;
+
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
@@ -37,6 +39,11 @@ public class SimpleMemberHandle implements MemberHandle
_port = port;
}
+ public SimpleMemberHandle(AMQShortString details)
+ {
+ this(details.toString());
+ }
+
public SimpleMemberHandle(String details)
{
String[] parts = details.split(":");
@@ -84,14 +91,14 @@ public class SimpleMemberHandle implements MemberHandle
return _host.equals(host) && _port == port;
}
- public String getDetails()
+ public AMQShortString getDetails()
{
- return _host + ":" + _port;
+ return new AMQShortString(_host + ":" + _port);
}
public String toString()
{
- return getDetails();
+ return getDetails().toString();
}
static List<MemberHandle> stringToMembers(String membership)
diff --git a/java/cluster/src/main/java/org/apache/qpid/server/cluster/SimpleSendable.java b/java/cluster/src/main/java/org/apache/qpid/server/cluster/SimpleSendable.java
index 34b5cd829d..8a3f288214 100644
--- a/java/cluster/src/main/java/org/apache/qpid/server/cluster/SimpleSendable.java
+++ b/java/cluster/src/main/java/org/apache/qpid/server/cluster/SimpleSendable.java
@@ -21,36 +21,24 @@
package org.apache.qpid.server.cluster;
import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQBody;
import org.apache.qpid.framing.AMQFrame;
+import org.apache.qpid.framing.MessageTransferBody;
+import org.apache.qpid.server.queue.AMQMessage;
-import java.util.Arrays;
-import java.util.List;
+import java.util.Iterator;
public class SimpleSendable implements Sendable
{
- private final List<AMQBody> _bodies;
+ private final AMQMessage _message;
- public SimpleSendable(AMQBody body)
+ public SimpleSendable(AMQMessage message)
{
- this(Arrays.asList(body));
- }
-
- public SimpleSendable(List<AMQBody> bodies)
- {
- _bodies = bodies;
+ _message = message;
}
public void send(int channel, Member member) throws AMQException
{
- for (AMQBody body : _bodies)
- {
- member.send(new AMQFrame(channel, body));
- }
- }
-
- public String toString()
- {
- return _bodies.toString();
+ // TODO: If refs are used, this will not work!
+ member.send(new AMQFrame(channel, _message.getTransferBody()));
}
}
diff --git a/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/ChainedClusterMethodHandler.java b/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/ChainedClusterMethodHandler.java
index 6cbacf4d27..d6e2aac165 100644
--- a/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/ChainedClusterMethodHandler.java
+++ b/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/ChainedClusterMethodHandler.java
@@ -25,6 +25,7 @@ import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.exchange.ExchangeRegistry;
import org.apache.qpid.server.protocol.AMQProtocolSession;
import org.apache.qpid.protocol.AMQMethodEvent;
+import org.apache.qpid.server.virtualhost.VirtualHostRegistry;
import org.apache.qpid.AMQException;
import org.apache.qpid.framing.AMQMethodBody;
@@ -54,19 +55,19 @@ public class ChainedClusterMethodHandler <A extends AMQMethodBody> extends Clust
}
}
- protected final void peer(AMQProtocolSession session, AMQMethodEvent<A> evt) throws AMQException
+ protected final void peer(AMQStateManager stateMgr, AMQMethodEvent<A> evt) throws AMQException
{
for(ClusterMethodHandler<A> handler : _handlers)
{
- handler.peer(session, evt);
+ handler.peer(stateMgr, evt);
}
}
- protected final void client(AMQProtocolSession session, AMQMethodEvent<A> evt) throws AMQException
+ protected final void client(AMQStateManager stateMgr, AMQMethodEvent<A> evt) throws AMQException
{
for(ClusterMethodHandler<A> handler : _handlers)
{
- handler.client(session, evt);
+ handler.client(stateMgr, evt);
}
}
}
diff --git a/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/ChannelQueueManager.java b/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/ChannelQueueManager.java
index f1ba4a0032..7bff211e76 100644
--- a/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/ChannelQueueManager.java
+++ b/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/ChannelQueueManager.java
@@ -27,8 +27,10 @@ import org.apache.qpid.server.exchange.ExchangeRegistry;
import org.apache.qpid.server.protocol.AMQProtocolSession;
import org.apache.qpid.protocol.AMQMethodEvent;
import org.apache.qpid.server.cluster.util.LogMessage;
+import org.apache.qpid.server.virtualhost.VirtualHostRegistry;
import org.apache.qpid.AMQException;
import org.apache.qpid.framing.AMQMethodBody;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.framing.QueueDeclareBody;
import org.apache.qpid.framing.QueueBindBody;
import org.apache.qpid.framing.QueueDeleteBody;
@@ -46,7 +48,7 @@ import java.util.HashMap;
class ChannelQueueManager
{
private static final Logger _logger = Logger.getLogger(ChannelQueueManager.class);
- private final Map<Integer, String> _channelQueues = new HashMap<Integer, String>();
+ private final Map<Integer, AMQShortString> _channelQueues = new HashMap<Integer, AMQShortString>();
ClusterMethodHandler<QueueDeclareBody> createQueueDeclareHandler()
{
@@ -68,37 +70,37 @@ class ChannelQueueManager
return new MessageConsumeHandler();
}
- private void set(int channel, String queue)
+ private void set(int channel, AMQShortString queue)
{
_channelQueues.put(channel, queue);
_logger.info(new LogMessage("Set default queue for {0} to {1}", channel, queue));
}
- private String get(int channel)
+ private AMQShortString get(int channel)
{
- String queue = _channelQueues.get(channel);
+ AMQShortString queue = _channelQueues.get(channel);
_logger.info(new LogMessage("Default queue for {0} is {1}", channel, queue));
return queue;
}
private class QueueDeclareHandler extends ClusterMethodHandler<QueueDeclareBody>
{
- protected void peer(AMQProtocolSession session, AMQMethodEvent<QueueDeclareBody> evt) throws AMQException
+ protected void peer(AMQStateManager stateMgr, AMQMethodEvent<QueueDeclareBody> evt) throws AMQException
{
}
- protected void client(AMQProtocolSession session, AMQMethodEvent<QueueDeclareBody> evt) throws AMQException
+ protected void client(AMQStateManager stateMgr, AMQMethodEvent<QueueDeclareBody> evt) throws AMQException
{
set(evt.getChannelId(), evt.getMethod().queue);
}
}
private class QueueBindHandler extends ClusterMethodHandler<QueueBindBody>
{
- protected void peer(AMQProtocolSession session, AMQMethodEvent<QueueBindBody> evt) throws AMQException
+ protected void peer(AMQStateManager stateMgr, AMQMethodEvent<QueueBindBody> evt) throws AMQException
{
}
- protected void client(AMQProtocolSession session, AMQMethodEvent<QueueBindBody> evt) throws AMQException
+ protected void client(AMQStateManager stateMgr, AMQMethodEvent<QueueBindBody> evt) throws AMQException
{
if(evt.getMethod().queue == null)
{
@@ -108,11 +110,11 @@ class ChannelQueueManager
}
private class QueueDeleteHandler extends ClusterMethodHandler<QueueDeleteBody>
{
- protected void peer(AMQProtocolSession session, AMQMethodEvent<QueueDeleteBody> evt) throws AMQException
+ protected void peer(AMQStateManager stateMgr, AMQMethodEvent<QueueDeleteBody> evt) throws AMQException
{
}
- protected void client(AMQProtocolSession session, AMQMethodEvent<QueueDeleteBody> evt) throws AMQException
+ protected void client(AMQStateManager stateMgr, AMQMethodEvent<QueueDeleteBody> evt) throws AMQException
{
if(evt.getMethod().queue == null)
{
@@ -123,11 +125,11 @@ class ChannelQueueManager
private class MessageConsumeHandler extends ClusterMethodHandler<MessageConsumeBody>
{
- protected void peer(AMQProtocolSession session, AMQMethodEvent<MessageConsumeBody> evt) throws AMQException
+ protected void peer(AMQStateManager stateMgr, AMQMethodEvent<MessageConsumeBody> evt) throws AMQException
{
}
- protected void client(AMQProtocolSession session, AMQMethodEvent<MessageConsumeBody> evt) throws AMQException
+ protected void client(AMQStateManager stateMgr, AMQMethodEvent<MessageConsumeBody> evt) throws AMQException
{
if(evt.getMethod().queue == null)
{
diff --git a/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/ClusterMethodHandler.java b/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/ClusterMethodHandler.java
index 25e7abe965..23a725571c 100644
--- a/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/ClusterMethodHandler.java
+++ b/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/ClusterMethodHandler.java
@@ -32,18 +32,20 @@ import org.apache.qpid.AMQException;
public abstract class ClusterMethodHandler<A extends AMQMethodBody> implements StateAwareMethodListener<A>
{
- public final void methodReceived(AMQProtocolSession session, AMQMethodEvent<A> evt) throws AMQException
+ public final void methodReceived(AMQStateManager stateMgr, AMQMethodEvent<A> evt) throws AMQException
{
+ AMQProtocolSession session = stateMgr.getProtocolSession();
+
if (ClusteredProtocolSession.isPeerSession(session))
{
- peer(session, evt);
+ peer(stateMgr, evt);
}
else
{
- client(session, evt);
+ client(stateMgr, evt);
}
}
- protected abstract void peer(AMQProtocolSession session, AMQMethodEvent<A> evt) throws AMQException;
- protected abstract void client(AMQProtocolSession session, AMQMethodEvent<A> evt) throws AMQException;
+ protected abstract void peer(AMQStateManager stateMgr, AMQMethodEvent<A> evt) throws AMQException;
+ protected abstract void client(AMQStateManager stateMgr, AMQMethodEvent<A> evt) throws AMQException;
}
diff --git a/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/ClusterMethodHandlerFactory.java b/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/ClusterMethodHandlerFactory.java
index 7ec4a5db0c..b502f910f1 100644
--- a/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/ClusterMethodHandlerFactory.java
+++ b/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/ClusterMethodHandlerFactory.java
@@ -23,6 +23,7 @@ package org.apache.qpid.server.cluster.handler;
import org.apache.qpid.AMQException;
import org.apache.qpid.framing.AMQFrame;
import org.apache.qpid.framing.AMQMethodBody;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.framing.MessageCancelBody;
import org.apache.qpid.framing.MessageConsumeBody;
import org.apache.qpid.framing.MessageTransferBody;
@@ -162,17 +163,15 @@ public class ClusterMethodHandlerFactory implements MethodHandlerFactory
private class SynchHandler implements StateAwareMethodListener<ClusterSynchBody>
{
- public void methodReceived(AMQProtocolSession session,
- AMQMethodEvent<ClusterSynchBody> evt) throws AMQException
+ public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<ClusterSynchBody> evt) throws AMQException
{
- _groupMgr.handleSynch(ClusteredProtocolSession.getSessionPeer(session));
+ _groupMgr.handleSynch(ClusteredProtocolSession.getSessionPeer(stateManager.getProtocolSession()));
}
}
private class JoinHandler implements StateAwareMethodListener<ClusterJoinBody>
{
- public void methodReceived(AMQProtocolSession session,
- AMQMethodEvent<ClusterJoinBody> evt) throws AMQException
+ public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<ClusterJoinBody> evt) throws AMQException
{
_groupMgr.handleJoin(new SimpleMemberHandle(evt.getMethod().broker));
}
@@ -180,8 +179,7 @@ public class ClusterMethodHandlerFactory implements MethodHandlerFactory
private class LeaveHandler implements StateAwareMethodListener<ClusterLeaveBody>
{
- public void methodReceived(AMQProtocolSession protocolSession,
- AMQMethodEvent<ClusterLeaveBody> evt) throws AMQException
+ public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<ClusterLeaveBody> evt) throws AMQException
{
_groupMgr.handleLeave(new SimpleMemberHandle(evt.getMethod().broker));
}
@@ -189,8 +187,7 @@ public class ClusterMethodHandlerFactory implements MethodHandlerFactory
private class SuspectHandler implements StateAwareMethodListener<ClusterSuspectBody>
{
- public void methodReceived(AMQProtocolSession protocolSession,
- AMQMethodEvent<ClusterSuspectBody> evt) throws AMQException
+ public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<ClusterSuspectBody> evt) throws AMQException
{
_groupMgr.handleSuspect(new SimpleMemberHandle(evt.getMethod().broker));
}
@@ -198,8 +195,7 @@ public class ClusterMethodHandlerFactory implements MethodHandlerFactory
private class MembershipHandler implements StateAwareMethodListener<ClusterMembershipBody>
{
- public void methodReceived(AMQProtocolSession session,
- AMQMethodEvent<ClusterMembershipBody> evt) throws AMQException
+ public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<ClusterMembershipBody> evt) throws AMQException
{
ClusterMembershipBody body = evt.getMethod();
_groupMgr.handleMembershipAnnouncement(new String(body.members));
@@ -208,15 +204,14 @@ public class ClusterMethodHandlerFactory implements MethodHandlerFactory
private class PingHandler implements StateAwareMethodListener<ClusterPingBody>
{
- public void methodReceived(AMQProtocolSession session,
- AMQMethodEvent<ClusterPingBody> evt) throws AMQException
+ public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<ClusterPingBody> evt) throws AMQException
{
MemberHandle peer = new SimpleMemberHandle(evt.getMethod().broker);
_groupMgr.handlePing(peer, evt.getMethod().load);
if (evt.getMethod().responseRequired)
{
evt.getMethod().load = _loadTable.getLocalLoad();
- session.writeFrame(new AMQFrame(evt.getChannelId(), evt.getMethod()));
+ stateManager.getProtocolSession().writeFrame(new AMQFrame(evt.getChannelId(), evt.getMethod()));
}
}
}
@@ -228,12 +223,12 @@ public class ClusterMethodHandlerFactory implements MethodHandlerFactory
super(ConnectionOpenMethodHandler.getInstance());
}
- void postHandle(AMQStateManager stateMgr, AMQProtocolSession session, AMQMethodEvent<ConnectionOpenBody> evt)
+ void postHandle(AMQStateManager stateMgr, AMQMethodEvent<ConnectionOpenBody> evt)
{
- String capabilities = evt.getMethod().capabilities;
+ AMQShortString capabilities = evt.getMethod().capabilities;
if (ClusterCapability.contains(capabilities))
{
- ClusteredProtocolSession.setSessionPeer(session, ClusterCapability.getPeer(capabilities));
+ ClusteredProtocolSession.setSessionPeer(stateMgr.getProtocolSession(), ClusterCapability.getPeer(capabilities));
}
else
{
@@ -249,9 +244,9 @@ public class ClusterMethodHandlerFactory implements MethodHandlerFactory
super(ConnectionCloseMethodHandler.getInstance());
}
- void postHandle(AMQStateManager stateMgr, AMQProtocolSession session, AMQMethodEvent<ConnectionCloseBody> evt)
+ void postHandle(AMQStateManager stateMgr, AMQMethodEvent<ConnectionCloseBody> evt)
{
- if (!ClusteredProtocolSession.isPeerSession(session))
+ if (!ClusteredProtocolSession.isPeerSession(stateMgr.getProtocolSession()))
{
_loadTable.decrementLocalLoad();
}
diff --git a/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/ExtendedHandler.java b/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/ExtendedHandler.java
index d05c7042d1..2316bc1795 100644
--- a/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/ExtendedHandler.java
+++ b/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/ExtendedHandler.java
@@ -38,18 +38,18 @@ class ExtendedHandler<A extends AMQMethodBody> implements StateAwareMethodListen
_base = base;
}
- public void methodReceived(AMQProtocolSession session, AMQMethodEvent<A> evt) throws AMQException
+ public void methodReceived(AMQStateManager stateMgr, AMQMethodEvent<A> evt) throws AMQException
{
- preHandle(session, evt);
- _base.methodReceived(session, evt);
- postHandle(session, evt);
+ preHandle(stateMgr, evt);
+ _base.methodReceived(stateMgr, evt);
+ postHandle(stateMgr, evt);
}
- void preHandle(AMQProtocolSession session, AMQMethodEvent<A> evt) throws AMQException
+ void preHandle(AMQStateManager stateMgr, AMQMethodEvent<A> evt) throws AMQException
{
}
- void postHandle(AMQProtocolSession session, AMQMethodEvent<A> evt) throws AMQException
+ void postHandle(AMQStateManager stateMgr, AMQMethodEvent<A> evt) throws AMQException
{
}
}
diff --git a/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/LocalQueueDeclareHandler.java b/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/LocalQueueDeclareHandler.java
index 1e6bc26444..f01a8349f2 100644
--- a/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/LocalQueueDeclareHandler.java
+++ b/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/LocalQueueDeclareHandler.java
@@ -23,6 +23,7 @@ package org.apache.qpid.server.cluster.handler;
import org.apache.log4j.Logger;
import org.apache.qpid.AMQException;
import org.apache.qpid.framing.QueueDeclareBody;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.server.cluster.ClusteredProtocolSession;
import org.apache.qpid.server.cluster.GroupManager;
import org.apache.qpid.server.cluster.util.LogMessage;
@@ -34,6 +35,7 @@ import org.apache.qpid.server.queue.ClusteredQueue;
import org.apache.qpid.server.queue.PrivateQueue;
import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.queue.RemoteQueueProxy;
+import org.apache.qpid.server.virtualhost.VirtualHost;
public class LocalQueueDeclareHandler extends QueueDeclareHandler
{
@@ -45,12 +47,12 @@ public class LocalQueueDeclareHandler extends QueueDeclareHandler
_groupMgr = groupMgr;
}
- protected String createName()
+ protected AMQShortString createName()
{
- return super.createName() + "@" + _groupMgr.getLocal().getDetails();
+ return new AMQShortString(super.createName().toString() + "@" + _groupMgr.getLocal().getDetails());
}
- protected AMQQueue createQueue(QueueDeclareBody body, QueueRegistry registry, AMQProtocolSession session) throws AMQException
+ protected AMQQueue createQueue(QueueDeclareBody body, VirtualHost virtualHost, AMQProtocolSession session) throws AMQException
{
//is it private or shared:
if (body.exclusive)
@@ -60,18 +62,18 @@ public class LocalQueueDeclareHandler extends QueueDeclareHandler
//need to get peer from the session...
MemberHandle peer = ClusteredProtocolSession.getSessionPeer(session);
_logger.debug(new LogMessage("Creating proxied queue {0} on behalf of {1}", body.queue, peer));
- return new RemoteQueueProxy(peer, _groupMgr, body.queue, body.durable, peer.getDetails(), body.autoDelete, registry);
+ return new RemoteQueueProxy(peer, _groupMgr, body.queue, body.durable, new AMQShortString(peer.getDetails()), body.autoDelete, virtualHost);
}
else
{
_logger.debug(new LogMessage("Creating local private queue {0}", body.queue));
- return new PrivateQueue(_groupMgr, body.queue, body.durable, session.getContextKey(), body.autoDelete, registry);
+ return new PrivateQueue(_groupMgr, body.queue, body.durable, session.getContextKey(), body.autoDelete, virtualHost);
}
}
else
{
_logger.debug(new LogMessage("Creating local shared queue {0}", body.queue));
- return new ClusteredQueue(_groupMgr, body.queue, body.durable, null, body.autoDelete, registry);
+ return new ClusteredQueue(_groupMgr, body.queue, body.durable, null, body.autoDelete, virtualHost);
}
}
}
diff --git a/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/NullListener.java b/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/NullListener.java
index 2d516ebcab..942df51c82 100644
--- a/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/NullListener.java
+++ b/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/NullListener.java
@@ -31,7 +31,7 @@ import org.apache.qpid.server.state.StateAwareMethodListener;
public class NullListener<T extends AMQMethodBody> implements StateAwareMethodListener<T>
{
- public void methodReceived(AMQProtocolSession protocolSession, AMQMethodEvent<T> evt) throws AMQException
+ public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<T> evt) throws AMQException
{
}
}
diff --git a/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/PeerHandler.java b/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/PeerHandler.java
index 1d115c2f9b..8df174d79d 100644
--- a/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/PeerHandler.java
+++ b/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/PeerHandler.java
@@ -47,14 +47,14 @@ public class PeerHandler<A extends AMQMethodBody> extends ClusterMethodHandler<A
_client = client;
}
- protected void peer(AMQProtocolSession session, AMQMethodEvent<A> evt) throws AMQException
+ protected void peer(AMQStateManager stateMgr, AMQMethodEvent<A> evt) throws AMQException
{
- _peer.methodReceived(session, evt);
+ _peer.methodReceived(stateMgr, evt);
}
- protected void client(AMQProtocolSession session, AMQMethodEvent<A> evt) throws AMQException
+ protected void client(AMQStateManager stateMgr, AMQMethodEvent<A> evt) throws AMQException
{
- _client.methodReceived(session, evt);
+ _client.methodReceived(stateMgr, evt);
}
}
diff --git a/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/QueueNameGenerator.java b/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/QueueNameGenerator.java
index c1b4c8b82c..d77d2bf965 100644
--- a/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/QueueNameGenerator.java
+++ b/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/QueueNameGenerator.java
@@ -41,11 +41,11 @@ class QueueNameGenerator extends ClusterMethodHandler<QueueDeclareBody>
_handler = handler;
}
- protected void peer(AMQProtocolSession session, AMQMethodEvent<QueueDeclareBody> evt) throws AMQException
+ protected void peer(AMQStateManager stateMgr, AMQMethodEvent<QueueDeclareBody> evt) throws AMQException
{
}
- protected void client(AMQProtocolSession session, AMQMethodEvent<QueueDeclareBody> evt)
+ protected void client(AMQStateManager stateMgr, AMQMethodEvent<QueueDeclareBody> evt)
throws AMQException
{
setName(evt.getMethod());//need to set the name before propagating this method
diff --git a/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/RemoteCancelHandler.java b/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/RemoteCancelHandler.java
index a278815324..abc1af9c4c 100644
--- a/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/RemoteCancelHandler.java
+++ b/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/RemoteCancelHandler.java
@@ -32,15 +32,21 @@ import org.apache.qpid.server.queue.ClusteredQueue;
import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.state.AMQStateManager;
import org.apache.qpid.server.state.StateAwareMethodListener;
+import org.apache.qpid.server.virtualhost.VirtualHost;
public class RemoteCancelHandler implements StateAwareMethodListener<MessageCancelBody>
{
private final Logger _logger = Logger.getLogger(RemoteCancelHandler.class);
- public void methodReceived(AMQProtocolSession session, AMQMethodEvent<MessageCancelBody> evt) throws AMQException
+ public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<MessageCancelBody> evt) throws AMQException
{
+ AMQProtocolSession session = stateManager.getProtocolSession();
+ VirtualHost virtualHost = session.getVirtualHost();
+ QueueRegistry queueRegistry = virtualHost.getQueueRegistry();
+
+
//By convention, consumers setup between brokers use the queue name as the consumer tag:
- AMQQueue queue = session.getQueueRegistry().getQueue(evt.getMethod().getDestination());
+ AMQQueue queue = queueRegistry.getQueue(evt.getMethod().getDestination());
if (queue instanceof ClusteredQueue)
{
((ClusteredQueue) queue).removeRemoteSubscriber(ClusteredProtocolSession.getSessionPeer(session));
diff --git a/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/RemoteConsumeHandler.java b/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/RemoteConsumeHandler.java
index e34ef38608..0b3569b6c3 100644
--- a/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/RemoteConsumeHandler.java
+++ b/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/RemoteConsumeHandler.java
@@ -33,6 +33,7 @@ import org.apache.qpid.server.queue.ClusteredQueue;
import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.state.AMQStateManager;
import org.apache.qpid.server.state.StateAwareMethodListener;
+import org.apache.qpid.server.virtualhost.VirtualHost;
/**
* Handles consume requests from other cluster members.
@@ -42,9 +43,13 @@ public class RemoteConsumeHandler implements StateAwareMethodListener<MessageCon
{
private final Logger _logger = Logger.getLogger(RemoteConsumeHandler.class);
- public void methodReceived(AMQProtocolSession session, AMQMethodEvent<MessageConsumeBody> evt) throws AMQException
+ public void methodReceived(AMQStateManager stateManager, AMQMethodEvent<MessageConsumeBody> evt) throws AMQException
{
- AMQQueue queue = session.getQueueRegistry().getQueue(evt.getMethod().queue);
+ AMQProtocolSession session = stateManager.getProtocolSession();
+ VirtualHost virtualHost = session.getVirtualHost();
+ QueueRegistry queueRegistry = virtualHost.getQueueRegistry();
+
+ AMQQueue queue = queueRegistry.getQueue(evt.getMethod().queue);
if (queue instanceof ClusteredQueue)
{
((ClusteredQueue) queue).addRemoteSubcriber(ClusteredProtocolSession.getSessionPeer(session));
diff --git a/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/ReplicatingConsumeHandler.java b/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/ReplicatingConsumeHandler.java
index 59df01fda4..4acf03335c 100644
--- a/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/ReplicatingConsumeHandler.java
+++ b/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/ReplicatingConsumeHandler.java
@@ -33,6 +33,7 @@ import org.apache.qpid.server.queue.AMQQueue;
import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.state.AMQStateManager;
import org.apache.qpid.server.state.StateAwareMethodListener;
+import org.apache.qpid.server.virtualhost.VirtualHost;
public class ReplicatingConsumeHandler extends ReplicatingHandler<MessageConsumeBody>
{
@@ -46,17 +47,22 @@ public class ReplicatingConsumeHandler extends ReplicatingHandler<MessageConsume
super(groupMgr, base(), policy);
}
- protected void replicate(AMQProtocolSession session, AMQMethodEvent<MessageConsumeBody> evt) throws AMQException
+ protected void replicate(AMQStateManager stateManager, AMQMethodEvent<MessageConsumeBody> evt) throws AMQException
{
+ AMQProtocolSession session = stateManager.getProtocolSession();
+ VirtualHost virtualHost = session.getVirtualHost();
+ ExchangeRegistry exchangeRegistry = virtualHost.getExchangeRegistry();
+ QueueRegistry queueRegistry = virtualHost.getQueueRegistry();
+
//only replicate if the queue in question is a shared queue
- if (isShared(session.getQueueRegistry().getQueue(evt.getMethod().queue)))
+ if (isShared(queueRegistry.getQueue(evt.getMethod().queue)))
{
- super.replicate(session, evt);
+ super.replicate(stateManager, evt);
}
else
{
_logger.info(new LogMessage("Handling consume for private queue ({0}) locally", evt.getMethod()));
- local(session, evt);
+ local(stateManager, evt);
_logger.info(new LogMessage("Handled consume for private queue ({0}) locally", evt.getMethod()));
}
diff --git a/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/ReplicatingHandler.java b/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/ReplicatingHandler.java
index ffc4325d63..29a76a1431 100644
--- a/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/ReplicatingHandler.java
+++ b/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/ReplicatingHandler.java
@@ -29,14 +29,14 @@ import org.apache.qpid.server.cluster.ClusteredProtocolSession;
import org.apache.qpid.server.cluster.GroupManager;
import org.apache.qpid.server.cluster.GroupResponseHandler;
import org.apache.qpid.server.cluster.util.LogMessage;
-import org.apache.qpid.server.cluster.Member;
-import org.apache.qpid.server.cluster.SimpleSendable;
+import org.apache.qpid.server.cluster.*;
import org.apache.qpid.server.cluster.policy.StandardPolicies;
import org.apache.qpid.server.exchange.ExchangeRegistry;
import org.apache.qpid.server.protocol.AMQProtocolSession;
import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.state.AMQStateManager;
import org.apache.qpid.server.state.StateAwareMethodListener;
+import org.apache.qpid.server.virtualhost.VirtualHost;
import java.util.List;
@@ -65,46 +65,51 @@ class ReplicatingHandler<A extends AMQMethodBody> extends ClusterMethodHandler<A
_policy = policy;
}
- protected void peer(AMQProtocolSession session, AMQMethodEvent<A> evt) throws AMQException
+ protected void peer(AMQStateManager stateManager, AMQMethodEvent<A> evt) throws AMQException
{
- local(session, evt);
+ AMQProtocolSession session = stateManager.getProtocolSession();
+ VirtualHost virtualHost = session.getVirtualHost();
+ ExchangeRegistry exchangeRegistry = virtualHost.getExchangeRegistry();
+ QueueRegistry queueRegistry = virtualHost.getQueueRegistry();
+
+ local(stateManager, evt);
_logger.debug(new LogMessage("Handled {0} locally", evt.getMethod()));
}
- protected void client(AMQProtocolSession session, AMQMethodEvent<A> evt) throws AMQException
+ protected void client(AMQStateManager stateMgr, AMQMethodEvent<A> evt) throws AMQException
{
- replicate(session, evt);
+ replicate(stateMgr, evt);
}
- protected void replicate(AMQProtocolSession session, AMQMethodEvent<A> evt) throws AMQException
+ protected void replicate(AMQStateManager stateMgr, AMQMethodEvent<A> evt) throws AMQException
{
if (_policy == null)
{
//asynch delivery
- _groupMgr.broadcast(new SimpleSendable(evt.getMethod()));
- local(session, evt);
+ _groupMgr.broadcast(new SimpleBodySendable(evt.getMethod()));
+ local(stateMgr, evt);
}
else
{
- Callback callback = new Callback(session, evt);
- _groupMgr.broadcast(new SimpleSendable(evt.getMethod()), _policy, callback);
+ Callback callback = new Callback(stateMgr, evt);
+ _groupMgr.broadcast(new SimpleBodySendable(evt.getMethod()), _policy, callback);
}
_logger.debug(new LogMessage("Replicated {0} to peers", evt.getMethod()));
}
- protected void local(AMQProtocolSession session, AMQMethodEvent<A> evt) throws AMQException
+ protected void local(AMQStateManager stateMgr, AMQMethodEvent<A> evt) throws AMQException
{
- _base.methodReceived(session, evt);
+ _base.methodReceived(stateMgr, evt);
}
private class Callback implements GroupResponseHandler
{
- private final AMQProtocolSession _session;
+ private final AMQStateManager _stateMgr;
private final AMQMethodEvent<A> _evt;
- Callback(AMQProtocolSession session, AMQMethodEvent<A> evt)
+ Callback(AMQStateManager stateMgr, AMQMethodEvent<A> evt)
{
- _session = session;
+ _stateMgr = stateMgr;
_evt = evt;
}
@@ -112,7 +117,7 @@ class ReplicatingHandler<A extends AMQMethodBody> extends ClusterMethodHandler<A
{
try
{
- local(_session, _evt);
+ local(_stateMgr, _evt);
_logger.debug(new LogMessage("Handled {0} locally, in response to completion of replication", _evt.getMethod()));
}
catch (AMQException e)
diff --git a/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/WrappedListener.java b/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/WrappedListener.java
index 62fbdf89d3..bf1659f1c5 100644
--- a/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/WrappedListener.java
+++ b/java/cluster/src/main/java/org/apache/qpid/server/cluster/handler/WrappedListener.java
@@ -42,11 +42,11 @@ public class WrappedListener<T extends AMQMethodBody> implements StateAwareMetho
_primary = check(primary);
}
- public void methodReceived(AMQProtocolSession session, AMQMethodEvent<T> evt) throws AMQException
+ public void methodReceived(AMQStateManager stateMgr, AMQMethodEvent<T> evt) throws AMQException
{
- _pre.methodReceived(session, evt);
- _primary.methodReceived(session, evt);
- _post.methodReceived(session, evt);
+ _pre.methodReceived(stateMgr, evt);
+ _primary.methodReceived(stateMgr, evt);
+ _post.methodReceived(stateMgr, evt);
}
private static <T extends AMQMethodBody> StateAwareMethodListener<T> check(StateAwareMethodListener<T> in)
diff --git a/java/cluster/src/main/java/org/apache/qpid/server/cluster/replay/ConsumerCounts.java b/java/cluster/src/main/java/org/apache/qpid/server/cluster/replay/ConsumerCounts.java
index b4249d70aa..9939e9f779 100644
--- a/java/cluster/src/main/java/org/apache/qpid/server/cluster/replay/ConsumerCounts.java
+++ b/java/cluster/src/main/java/org/apache/qpid/server/cluster/replay/ConsumerCounts.java
@@ -22,6 +22,7 @@ package org.apache.qpid.server.cluster.replay;
import org.apache.qpid.framing.AMQMethodBody;
import org.apache.qpid.framing.MessageConsumeBody;
+import org.apache.qpid.framing.AMQShortString;
import java.util.Map;
import java.util.HashMap;
@@ -29,19 +30,19 @@ import java.util.List;
class ConsumerCounts
{
- private final Map<String, Integer> _counts = new HashMap<String, Integer>();
+ private final Map<AMQShortString, Integer> _counts = new HashMap<AMQShortString, Integer>();
- synchronized void increment(String queue)
+ synchronized void increment(AMQShortString queue)
{
_counts.put(queue, get(queue) + 1);
}
- synchronized void decrement(String queue)
+ synchronized void decrement(AMQShortString queue)
{
_counts.put(queue, get(queue) - 1);
}
- private int get(String queue)
+ private int get(AMQShortString queue)
{
Integer count = _counts.get(queue);
return count == null ? 0 : count;
@@ -49,13 +50,21 @@ class ConsumerCounts
synchronized void replay(List<AMQMethodBody> messages)
{
- for(String queue : _counts.keySet())
+ for(AMQShortString queue : _counts.keySet())
{
// AMQP version change: Hardwire the version to 0-9 (major=0, minor=9)
// TODO: Connect this to the session version obtained from ProtocolInitiation for this session.
- MessageConsumeBody m = new MessageConsumeBody((byte)0, (byte)9);
- m.queue = queue;
- m.destination = queue;
+ MessageConsumeBody m = new MessageConsumeBody((byte)0,
+ (byte)9,
+ MessageConsumeBody.getClazz((byte)0, (byte)9),
+ MessageConsumeBody.getMethod((byte)0, (byte)9),
+ queue, // AMQShortString destination
+ false, // boolean exclusive
+ null, // FieldTable filter
+ false, // boolean noAck
+ false, // boolean noLocal
+ queue, // AMQShortString queue
+ 0); // int ticket
replay(m, messages);
}
}
diff --git a/java/cluster/src/main/java/org/apache/qpid/server/cluster/replay/RecordingMethodHandlerFactory.java b/java/cluster/src/main/java/org/apache/qpid/server/cluster/replay/RecordingMethodHandlerFactory.java
index 2675fbb1f4..e38a1bc3d9 100644
--- a/java/cluster/src/main/java/org/apache/qpid/server/cluster/replay/RecordingMethodHandlerFactory.java
+++ b/java/cluster/src/main/java/org/apache/qpid/server/cluster/replay/RecordingMethodHandlerFactory.java
@@ -22,6 +22,7 @@ package org.apache.qpid.server.cluster.replay;
import org.apache.qpid.AMQException;
import org.apache.qpid.framing.AMQMethodBody;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.framing.MessageCancelBody;
import org.apache.qpid.framing.MessageConsumeBody;
import org.apache.qpid.framing.ExchangeDeclareBody;
@@ -50,13 +51,13 @@ public class RecordingMethodHandlerFactory extends WrappingMethodHandlerFactory
private final byte minor = (byte)9;
private final Iterable<FrameDescriptor> _frames = Arrays.asList(new FrameDescriptor[]
{
- new FrameDescriptor(QueueDeclareBody.class, new QueueDeclareBody(major, minor)),
- new FrameDescriptor(QueueDeleteBody.class, new QueueDeleteBody(major, minor)),
- new FrameDescriptor(QueueBindBody.class, new QueueBindBody(major, minor)),
- new FrameDescriptor(ExchangeDeclareBody.class, new ExchangeDeclareBody(major, minor)),
- new FrameDescriptor(ExchangeDeleteBody.class, new ExchangeDeleteBody(major, minor)),
- new FrameDescriptor(MessageConsumeBody.class, new MessageConsumeBody(major, minor)),
- new FrameDescriptor(MessageCancelBody.class, new MessageCancelBody(major, minor))
+ new FrameDescriptor(QueueDeclareBody.class, new QueueDeclareBody(major, minor, QueueDeclareBody.getClazz(major, minor), QueueDeclareBody.getMethod(major, minor),null,false,false,false,false,false,null,0)),
+ new FrameDescriptor(QueueDeleteBody.class, new QueueDeleteBody(major, minor, QueueDeleteBody.getClazz(major, minor), QueueDeleteBody.getMethod(major, minor),false,false,false,null,0)),
+ new FrameDescriptor(QueueBindBody.class, new QueueBindBody(major, minor, QueueBindBody.getClazz(major, minor), QueueBindBody.getMethod(major, minor),null,null,false,null,null,0)),
+ new FrameDescriptor(ExchangeDeclareBody.class, new ExchangeDeclareBody(major, minor, ExchangeDeclareBody.getClazz(major, minor), ExchangeDeclareBody.getMethod(major, minor),null,false,false,null,false,false,false,0,null)),
+ new FrameDescriptor(ExchangeDeleteBody.class, new ExchangeDeleteBody(major, minor, ExchangeDeleteBody.getClazz(major, minor), ExchangeDeleteBody.getMethod(major, minor),null,false,false,0)),
+ new FrameDescriptor(MessageConsumeBody.class, new MessageConsumeBody(major, minor, MessageConsumeBody.getClazz(major, minor), MessageConsumeBody.getMethod(major, minor),null,false,null,false,false,null,0)),
+ new FrameDescriptor(MessageCancelBody.class, new MessageCancelBody(major, minor, MessageCancelBody.getClazz(major, minor), MessageCancelBody.getMethod(major, minor),(AMQShortString)null))
});
diff --git a/java/cluster/src/main/java/org/apache/qpid/server/cluster/replay/ReplayStore.java b/java/cluster/src/main/java/org/apache/qpid/server/cluster/replay/ReplayStore.java
index b82e3ad0ac..3c3e0c107b 100644
--- a/java/cluster/src/main/java/org/apache/qpid/server/cluster/replay/ReplayStore.java
+++ b/java/cluster/src/main/java/org/apache/qpid/server/cluster/replay/ReplayStore.java
@@ -23,6 +23,7 @@ package org.apache.qpid.server.cluster.replay;
import org.apache.log4j.Logger;
import org.apache.qpid.AMQException;
import org.apache.qpid.framing.AMQMethodBody;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.framing.ExchangeDeclareBody;
import org.apache.qpid.framing.ExchangeDeleteBody;
import org.apache.qpid.framing.QueueBindBody;
@@ -40,6 +41,7 @@ import org.apache.qpid.server.protocol.AMQProtocolSession;
import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.state.AMQStateManager;
import org.apache.qpid.server.state.StateAwareMethodListener;
+import org.apache.qpid.server.virtualhost.VirtualHost;
import java.util.ArrayList;
import java.util.HashMap;
@@ -57,11 +59,11 @@ public class ReplayStore implements ReplayManager, StateAwareMethodListener
private final Map<Class<? extends AMQMethodBody>, MethodRecorder> _globalRecorders = new HashMap<Class<? extends AMQMethodBody>, MethodRecorder>();
private final Map<Class<? extends AMQMethodBody>, MethodRecorder> _localRecorders = new HashMap<Class<? extends AMQMethodBody>, MethodRecorder>();
- private final Map<String, QueueDeclareBody> _sharedQueues = new ConcurrentHashMap<String, QueueDeclareBody>();
- private final Map<String, QueueDeclareBody> _privateQueues = new ConcurrentHashMap<String, QueueDeclareBody>();
- private final Bindings<String, String, QueueBindBody> _sharedBindings = new Bindings<String, String, QueueBindBody>();
- private final Bindings<String, String, QueueBindBody> _privateBindings = new Bindings<String, String, QueueBindBody>();
- private final Map<String, ExchangeDeclareBody> _exchanges = new ConcurrentHashMap<String, ExchangeDeclareBody>();
+ private final Map<AMQShortString, QueueDeclareBody> _sharedQueues = new ConcurrentHashMap<AMQShortString, QueueDeclareBody>();
+ private final Map<AMQShortString, QueueDeclareBody> _privateQueues = new ConcurrentHashMap<AMQShortString, QueueDeclareBody>();
+ private final Bindings<AMQShortString, AMQShortString, QueueBindBody> _sharedBindings = new Bindings<AMQShortString, AMQShortString, QueueBindBody>();
+ private final Bindings<AMQShortString, AMQShortString, QueueBindBody> _privateBindings = new Bindings<AMQShortString, AMQShortString, QueueBindBody>();
+ private final Map<AMQShortString, ExchangeDeclareBody> _exchanges = new ConcurrentHashMap<AMQShortString, ExchangeDeclareBody>();
private final ConsumerCounts _consumers = new ConsumerCounts();
public ReplayStore()
@@ -81,8 +83,11 @@ public class ReplayStore implements ReplayManager, StateAwareMethodListener
_localRecorders.put(ExchangeDeleteBody.class, new ExchangeDeleteRecorder());
}
- public void methodReceived(AMQProtocolSession session, AMQMethodEvent evt) throws AMQException
+ public void methodReceived(AMQStateManager stateManager, AMQMethodEvent evt) throws AMQException
{
+ AMQProtocolSession session = stateManager.getProtocolSession();
+ VirtualHost virtualHost = session.getVirtualHost();
+
_logger.debug(new LogMessage("Replay store received {0}", evt.getMethod()));
AMQMethodBody request = evt.getMethod();
@@ -126,7 +131,7 @@ public class ReplayStore implements ReplayManager, StateAwareMethodListener
_consumers.replay(methods);
// AMQP version change: Hardwire the version to 0-9 (major=0, minor=9)
// TODO: Connect this to the session version obtained from ProtocolInitiation for this session.
- methods.add(new ClusterSynchBody((byte)0, (byte)9));
+ methods.add(new ClusterSynchBody((byte)0, (byte)9, ClusterSynchBody.getClazz((byte)0, (byte)9), ClusterSynchBody.getMethod((byte)0, (byte)9)));
return methods;
}
@@ -204,15 +209,15 @@ public class ReplayStore implements ReplayManager, StateAwareMethodListener
private static class QueueDeclareRecorder extends ChainedMethodRecorder<QueueDeclareBody>
{
private final boolean _exclusive;
- private final Map<String, QueueDeclareBody> _queues;
+ private final Map<AMQShortString, QueueDeclareBody> _queues;
- QueueDeclareRecorder(boolean exclusive, Map<String, QueueDeclareBody> queues)
+ QueueDeclareRecorder(boolean exclusive, Map<AMQShortString, QueueDeclareBody> queues)
{
_queues = queues;
_exclusive = exclusive;
}
- QueueDeclareRecorder(boolean exclusive, Map<String, QueueDeclareBody> queues, QueueDeclareRecorder recorder)
+ QueueDeclareRecorder(boolean exclusive, Map<AMQShortString, QueueDeclareBody> queues, QueueDeclareRecorder recorder)
{
super(recorder);
_queues = queues;
@@ -236,15 +241,15 @@ public class ReplayStore implements ReplayManager, StateAwareMethodListener
private class QueueDeleteRecorder extends ChainedMethodRecorder<QueueDeleteBody>
{
- private final Map<String, QueueDeclareBody> _queues;
- private final Bindings<String, String, QueueBindBody> _bindings;
+ private final Map<AMQShortString, QueueDeclareBody> _queues;
+ private final Bindings<AMQShortString, AMQShortString, QueueBindBody> _bindings;
- QueueDeleteRecorder(Map<String, QueueDeclareBody> queues, Bindings<String, String, QueueBindBody> bindings)
+ QueueDeleteRecorder(Map<AMQShortString, QueueDeclareBody> queues, Bindings<AMQShortString, AMQShortString, QueueBindBody> bindings)
{
this(queues, bindings, null);
}
- QueueDeleteRecorder(Map<String, QueueDeclareBody> queues, Bindings<String, String, QueueBindBody> bindings, QueueDeleteRecorder recorder)
+ QueueDeleteRecorder(Map<AMQShortString, QueueDeclareBody> queues, Bindings<AMQShortString, AMQShortString, QueueBindBody> bindings, QueueDeleteRecorder recorder)
{
super(recorder);
_queues = queues;
@@ -267,16 +272,16 @@ public class ReplayStore implements ReplayManager, StateAwareMethodListener
private class QueueBindRecorder extends ChainedMethodRecorder<QueueBindBody>
{
- private final Map<String, QueueDeclareBody> _queues;
- private final Bindings<String, String, QueueBindBody> _bindings;
+ private final Map<AMQShortString, QueueDeclareBody> _queues;
+ private final Bindings<AMQShortString, AMQShortString, QueueBindBody> _bindings;
- QueueBindRecorder(Map<String, QueueDeclareBody> queues, Bindings<String, String, QueueBindBody> bindings)
+ QueueBindRecorder(Map<AMQShortString, QueueDeclareBody> queues, Bindings<AMQShortString, AMQShortString, QueueBindBody> bindings)
{
_queues = queues;
_bindings = bindings;
}
- QueueBindRecorder(Map<String, QueueDeclareBody> queues, Bindings<String, String, QueueBindBody> bindings, QueueBindRecorder recorder)
+ QueueBindRecorder(Map<AMQShortString, QueueDeclareBody> queues, Bindings<AMQShortString, AMQShortString, QueueBindBody> bindings, QueueBindRecorder recorder)
{
super(recorder);
_queues = queues;
diff --git a/java/cluster/src/main/java/org/apache/qpid/server/queue/ClusteredQueue.java b/java/cluster/src/main/java/org/apache/qpid/server/queue/ClusteredQueue.java
index 3b9f95be46..41fc341c86 100644
--- a/java/cluster/src/main/java/org/apache/qpid/server/queue/ClusteredQueue.java
+++ b/java/cluster/src/main/java/org/apache/qpid/server/queue/ClusteredQueue.java
@@ -24,9 +24,12 @@ import org.apache.log4j.Logger;
import org.apache.qpid.AMQException;
import org.apache.qpid.framing.MessageCancelBody;
import org.apache.qpid.framing.QueueDeleteBody;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.server.cluster.*;
import org.apache.qpid.server.cluster.util.LogMessage;
import org.apache.qpid.server.protocol.AMQProtocolSession;
+import org.apache.qpid.server.store.StoreContext;
+import org.apache.qpid.server.virtualhost.VirtualHost;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
@@ -44,27 +47,19 @@ public class ClusteredQueue extends AMQQueue
private final GroupManager _groupMgr;
private final NestedSubscriptionManager _subscriptions;
- public ClusteredQueue(GroupManager groupMgr, String name, boolean durable, String owner, boolean autoDelete, QueueRegistry queueRegistry)
+ public ClusteredQueue(GroupManager groupMgr, AMQShortString name, boolean durable, AMQShortString owner, boolean autoDelete, VirtualHost virtualHost)
throws AMQException
{
- super(name, durable, owner, autoDelete, queueRegistry, new ClusteredSubscriptionManager());
+ super(name, durable, owner, autoDelete, virtualHost, new ClusteredSubscriptionManager());
_groupMgr = groupMgr;
_subscriptions = ((ClusteredSubscriptionManager) getSubscribers()).getAllSubscribers();
}
- public ClusteredQueue(GroupManager groupMgr, String name, boolean durable, String owner, boolean autoDelete, QueueRegistry queueRegistry, Executor asyncDelivery)
- throws AMQException
- {
- super(name, durable, owner, autoDelete, queueRegistry, asyncDelivery, new ClusteredSubscriptionManager(),
- new SubscriptionImpl.Factory());
- _groupMgr = groupMgr;
- _subscriptions = ((ClusteredSubscriptionManager) getSubscribers()).getAllSubscribers();
- }
- public void deliver(AMQMessage message) throws AMQException
+ public void process(StoreContext storeContext, AMQMessage msg) throws AMQException
{
- _logger.info(new LogMessage("{0} delivered to clustered queue {1}", message, this));
- super.deliver(message);
+ _logger.info(new LogMessage("{0} delivered to clustered queue {1}", msg, this));
+ super.process(storeContext, msg);
}
protected void autodelete() throws AMQException
@@ -77,13 +72,21 @@ public class ClusteredQueue extends AMQQueue
//send deletion request to all other members:
// AMQP version change: Hardwire the version to 0-9 (major=0, minor=9)
// TODO: Connect this to the session version obtained from ProtocolInitiation for this session.
- QueueDeleteBody request = new QueueDeleteBody((byte)0, (byte)9);
- request.queue = getName();
- _groupMgr.broadcast(new SimpleSendable(request));
+ QueueDeleteBody request = new QueueDeleteBody((byte)0,
+ (byte)9,
+ QueueDeleteBody.getClazz((byte)0,(byte)9),
+ QueueDeleteBody.getMethod((byte)0,(byte)9),
+ false,
+ false,
+ false,
+ getName(),
+ 0);
+
+ _groupMgr.broadcast(new SimpleBodySendable(request));
}
}
- public void unregisterProtocolSession(AMQProtocolSession ps, int channel, String consumerTag) throws AMQException
+ public void unregisterProtocolSession(AMQProtocolSession ps, int channel, AMQShortString consumerTag) throws AMQException
{
//handle locally:
super.unregisterProtocolSession(ps, channel, consumerTag);
@@ -91,9 +94,13 @@ public class ClusteredQueue extends AMQQueue
//signal other members:
// AMQP version change: Hardwire the version to 0-9 (major=0, minor=9)
// TODO: Connect this to the session version obtained from ProtocolInitiation for this session.
- MessageCancelBody request = new MessageCancelBody((byte)0, (byte)9);
- request.destination = getName();
- _groupMgr.broadcast(new SimpleSendable(request));
+ MessageCancelBody request = new MessageCancelBody((byte)0,
+ (byte)9,
+ MessageCancelBody.getClazz((byte)0, (byte)9),
+ MessageCancelBody.getMethod((byte)0, (byte)9),
+ getName());
+
+ _groupMgr.broadcast(new SimpleBodySendable(request));
}
public void addRemoteSubcriber(MemberHandle peer)
diff --git a/java/cluster/src/main/java/org/apache/qpid/server/queue/PrivateQueue.java b/java/cluster/src/main/java/org/apache/qpid/server/queue/PrivateQueue.java
index 2e291b0a3a..570f69b6a5 100644
--- a/java/cluster/src/main/java/org/apache/qpid/server/queue/PrivateQueue.java
+++ b/java/cluster/src/main/java/org/apache/qpid/server/queue/PrivateQueue.java
@@ -23,7 +23,10 @@ package org.apache.qpid.server.queue;
import org.apache.qpid.AMQException;
import org.apache.qpid.server.cluster.SimpleSendable;
import org.apache.qpid.server.cluster.GroupManager;
+import org.apache.qpid.server.cluster.SimpleBodySendable;
+import org.apache.qpid.server.virtualhost.VirtualHost;
import org.apache.qpid.framing.QueueDeleteBody;
+import org.apache.qpid.framing.AMQShortString;
import java.util.concurrent.Executor;
@@ -35,21 +38,14 @@ public class PrivateQueue extends AMQQueue
{
private final GroupManager _groupMgr;
- public PrivateQueue(GroupManager groupMgr, String name, boolean durable, String owner, boolean autoDelete, QueueRegistry queueRegistry)
+ public PrivateQueue(GroupManager groupMgr, AMQShortString name, boolean durable, AMQShortString owner, boolean autoDelete, VirtualHost virtualHost)
throws AMQException
{
- super(name, durable, owner, autoDelete, queueRegistry);
+ super(name, durable, owner, autoDelete, virtualHost);
_groupMgr = groupMgr;
}
- public PrivateQueue(GroupManager groupMgr, String name, boolean durable, String owner, boolean autoDelete, QueueRegistry queueRegistry, Executor asyncDelivery)
- throws AMQException
- {
- super(name, durable, owner, autoDelete, queueRegistry, asyncDelivery);
- _groupMgr = groupMgr;
- }
-
protected void autodelete() throws AMQException
{
//delete locally:
@@ -58,8 +54,11 @@ public class PrivateQueue extends AMQQueue
//send delete request to peers:
// AMQP version change: Hardwire the version to 0-9 (major=0, minor=9)
// TODO: Connect this to the session version obtained from ProtocolInitiation for this session.
- QueueDeleteBody request = new QueueDeleteBody((byte)0, (byte)9);
+ QueueDeleteBody request = new QueueDeleteBody((byte)8, (byte)0,
+ QueueDeleteBody.getClazz((byte)8, (byte)0),
+ QueueDeleteBody.getMethod((byte)8, (byte)0),
+ false,false,false,null,0);
request.queue = getName();
- _groupMgr.broadcast(new SimpleSendable(request));
+ _groupMgr.broadcast(new SimpleBodySendable(request));
}
}
diff --git a/java/cluster/src/main/java/org/apache/qpid/server/queue/RemoteQueueProxy.java b/java/cluster/src/main/java/org/apache/qpid/server/queue/RemoteQueueProxy.java
index a989e45708..cc6b17092f 100644
--- a/java/cluster/src/main/java/org/apache/qpid/server/queue/RemoteQueueProxy.java
+++ b/java/cluster/src/main/java/org/apache/qpid/server/queue/RemoteQueueProxy.java
@@ -22,17 +22,16 @@ package org.apache.qpid.server.queue;
import org.apache.log4j.Logger;
import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.AMQBody;
import org.apache.qpid.framing.MessageTransferBody;
import org.apache.qpid.framing.Content;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.server.cluster.ClusteredProtocolSession;
import org.apache.qpid.server.cluster.GroupManager;
-import org.apache.qpid.server.cluster.util.LogMessage;
import org.apache.qpid.server.cluster.MemberHandle;
import org.apache.qpid.server.cluster.SimpleSendable;
+import org.apache.qpid.server.cluster.util.LogMessage;
+import org.apache.qpid.server.virtualhost.VirtualHost;
-import java.util.ArrayList;
-import java.util.List;
import java.util.concurrent.Executor;
/**
@@ -46,23 +45,15 @@ public class RemoteQueueProxy extends AMQQueue
private final MemberHandle _target;
private final GroupManager _groupMgr;
- public RemoteQueueProxy(MemberHandle target, GroupManager groupMgr, String name, boolean durable, String owner, boolean autoDelete, QueueRegistry queueRegistry)
+ public RemoteQueueProxy(MemberHandle target, GroupManager groupMgr, AMQShortString name, boolean durable, AMQShortString owner, boolean autoDelete, VirtualHost virtualHost)
throws AMQException
{
- super(name, durable, owner, autoDelete, queueRegistry);
+ super(name, durable, owner, autoDelete, virtualHost);
_target = target;
_groupMgr = groupMgr;
_groupMgr.addMemberhipChangeListener(new ProxiedQueueCleanup(target, this));
}
- public RemoteQueueProxy(MemberHandle target, GroupManager groupMgr, String name, boolean durable, String owner, boolean autoDelete, QueueRegistry queueRegistry, Executor asyncDelivery)
- throws AMQException
- {
- super(name, durable, owner, autoDelete, queueRegistry, asyncDelivery);
- _target = target;
- _groupMgr = groupMgr;
- _groupMgr.addMemberhipChangeListener(new ProxiedQueueCleanup(target, this));
- }
public void deliver(AMQMessage msg) throws NoConsumersException
{
@@ -94,18 +85,15 @@ public class RemoteQueueProxy extends AMQQueue
throw new Error("XXX");
/*
MessageTransferBody publish = msg.getPublishBody();
+<<<<<<< .working
ContentHeaderBody header = msg.getContentHeaderBody();
List<Content> bodies = msg.getContentBodies();
+=======
+ publish.immediate = false; //can't as yet handle the immediate flag in a cluster
+>>>>>>> .merge-right.r501854
- //(i) construct a new publishing block:
- publish.immediate = false;//can't as yet handle the immediate flag in a cluster
- List<AMQBody> parts = new ArrayList<AMQBody>(2 + bodies.size());
- parts.add(publish);
- parts.add(header);
- parts.addAll(bodies);
-
- //(ii) send this on to the broker for which it is acting as proxy:
- _groupMgr.send(_target, new SimpleSendable(parts));
+ // send this on to the broker for which it is acting as proxy:
+ _groupMgr.send(_target, new SimpleSendable(msg));
*/
}
}
diff --git a/java/cluster/src/main/java/org/apache/qpid/server/queue/RemoteSubscriptionImpl.java b/java/cluster/src/main/java/org/apache/qpid/server/queue/RemoteSubscriptionImpl.java
index c751e4a011..364aea81c0 100644
--- a/java/cluster/src/main/java/org/apache/qpid/server/queue/RemoteSubscriptionImpl.java
+++ b/java/cluster/src/main/java/org/apache/qpid/server/queue/RemoteSubscriptionImpl.java
@@ -55,7 +55,7 @@ class RemoteSubscriptionImpl implements Subscription, WeightedSubscriptionManage
{
try
{
- _groupMgr.send(_peer, new SimpleSendable(msg.getPayload()));
+ _groupMgr.send(_peer, new SimpleSendable(msg));
}
catch (AMQException e)
{
@@ -134,11 +134,12 @@ class RemoteSubscriptionImpl implements Subscription, WeightedSubscriptionManage
public boolean isBrowser()
{
- return false; //To change body of implemented methods use File | Settings | File Templates.
+ return false;
}
- public void sendNextMessage(AMQQueue queue)
+ public boolean wouldSuspend(AMQMessage msg)
{
-
+ return _suspended;
}
+
}
diff --git a/java/cluster/src/test/java/org/apache/qpid/server/cluster/BrokerTest.java b/java/cluster/src/test/java/org/apache/qpid/server/cluster/BrokerTest.java
index 583cc35ab3..074db547f7 100644
--- a/java/cluster/src/test/java/org/apache/qpid/server/cluster/BrokerTest.java
+++ b/java/cluster/src/test/java/org/apache/qpid/server/cluster/BrokerTest.java
@@ -45,7 +45,7 @@ public class BrokerTest extends TestCase
new RecordingBroker("C", 3)
};
GroupResponseValidator handler = new GroupResponseValidator(new TestMethod("response"), new ArrayList<Member>(Arrays.asList(brokers)));
- GroupRequest grpRequest = new GroupRequest(new SimpleSendable(new TestMethod("request")), StandardPolicies.SYNCH_POLICY, handler);
+ GroupRequest grpRequest = new GroupRequest(new SimpleBodySendable(new TestMethod("request")), StandardPolicies.SYNCH_POLICY, handler);
for (Broker b : brokers)
{
b.invoke(grpRequest);
@@ -54,7 +54,7 @@ public class BrokerTest extends TestCase
for (RecordingBroker b : brokers)
{
- b.handleResponse(((AMQFrame) b.getMessages().get(0)).channel, new TestMethod("response"));
+ b.handleResponse(((AMQFrame) b.getMessages().get(0)).getChannel(), new TestMethod("response"));
}
assertTrue("Handler did not receive response", handler.isCompleted());
@@ -70,7 +70,7 @@ public class BrokerTest extends TestCase
RecordingBroker[] succeeded = new RecordingBroker[]{a, c};
GroupResponseValidator handler = new GroupResponseValidator(new TestMethod("response"), new ArrayList<Member>(Arrays.asList(succeeded)));
- GroupRequest grpRequest = new GroupRequest(new SimpleSendable(new TestMethod("request")), StandardPolicies.SYNCH_POLICY, handler);
+ GroupRequest grpRequest = new GroupRequest(new SimpleBodySendable(new TestMethod("request")), StandardPolicies.SYNCH_POLICY, handler);
for (Broker broker : all)
{
@@ -80,7 +80,7 @@ public class BrokerTest extends TestCase
for (RecordingBroker broker : succeeded)
{
- broker.handleResponse(((AMQFrame) broker.getMessages().get(0)).channel, new TestMethod("response"));
+ broker.handleResponse(((AMQFrame) broker.getMessages().get(0)).getChannel(), new TestMethod("response"));
}
b.remove();
@@ -99,14 +99,14 @@ public class BrokerTest extends TestCase
RecordingBroker broker = new RecordingBroker("myhost", 1);
for (AMQBody msg : msgs)
{
- broker.send(new SimpleSendable(msg), null);
+ broker.send(new SimpleBodySendable(msg), null);
}
List<AMQDataBlock> sent = broker.getMessages();
assertEquals(msgs.length, sent.size());
for (int i = 0; i < msgs.length; i++)
{
assertTrue(sent.get(i) instanceof AMQFrame);
- assertEquals(msgs[i], ((AMQFrame) sent.get(i)).bodyFrame);
+ assertEquals(msgs[i], ((AMQFrame) sent.get(i)).getBodyFrame());
}
}
@@ -115,13 +115,13 @@ public class BrokerTest extends TestCase
{
RecordingBroker broker = new RecordingBroker("myhost", 1);
BlockingHandler handler = new BlockingHandler();
- broker.send(new SimpleSendable(new TestMethod("A")), handler);
+ broker.send(new SimpleBodySendable(new TestMethod("A")), handler);
List<AMQDataBlock> sent = broker.getMessages();
assertEquals(1, sent.size());
assertTrue(sent.get(0) instanceof AMQFrame);
- assertEquals(new TestMethod("A"), ((AMQFrame) sent.get(0)).bodyFrame);
+ assertEquals(new TestMethod("A"), ((AMQFrame) sent.get(0)).getBodyFrame());
- broker.handleResponse(((AMQFrame) sent.get(0)).channel, new TestMethod("B"));
+ broker.handleResponse(((AMQFrame) sent.get(0)).getChannel(), new TestMethod("B"));
assertEquals(new TestMethod("B"), handler.getResponse());
}
@@ -131,11 +131,11 @@ public class BrokerTest extends TestCase
{
RecordingBroker broker = new RecordingBroker("myhost", 1);
BlockingHandler handler = new BlockingHandler();
- broker.send(new SimpleSendable(new TestMethod("A")), handler);
+ broker.send(new SimpleBodySendable(new TestMethod("A")), handler);
List<AMQDataBlock> sent = broker.getMessages();
assertEquals(1, sent.size());
assertTrue(sent.get(0) instanceof AMQFrame);
- assertEquals(new TestMethod("A"), ((AMQFrame) sent.get(0)).bodyFrame);
+ assertEquals(new TestMethod("A"), ((AMQFrame) sent.get(0)).getBodyFrame());
broker.remove();
assertEquals(null, handler.getResponse());
assertTrue(handler.isCompleted());
diff --git a/java/cluster/src/test/java/org/apache/qpid/server/cluster/ClusterCapabilityTest.java b/java/cluster/src/test/java/org/apache/qpid/server/cluster/ClusterCapabilityTest.java
index 76b1da8754..830a00f4c2 100644
--- a/java/cluster/src/test/java/org/apache/qpid/server/cluster/ClusterCapabilityTest.java
+++ b/java/cluster/src/test/java/org/apache/qpid/server/cluster/ClusterCapabilityTest.java
@@ -21,13 +21,14 @@
package org.apache.qpid.server.cluster;
import junit.framework.TestCase;
+import org.apache.qpid.framing.AMQShortString;
public class ClusterCapabilityTest extends TestCase
{
public void testStartWithNull()
{
MemberHandle peer = new SimpleMemberHandle("myhost:9999");
- String c = ClusterCapability.add(null, peer);
+ AMQShortString c = ClusterCapability.add(null, peer);
assertTrue(ClusterCapability.contains(c));
assertTrue(peer.matches(ClusterCapability.getPeer(c)));
}
@@ -35,7 +36,7 @@ public class ClusterCapabilityTest extends TestCase
public void testStartWithText()
{
MemberHandle peer = new SimpleMemberHandle("myhost:9999");
- String c = ClusterCapability.add("existing text", peer);
+ AMQShortString c = ClusterCapability.add(new AMQShortString("existing text"), peer);
assertTrue(ClusterCapability.contains(c));
assertTrue(peer.matches(ClusterCapability.getPeer(c)));
}
diff --git a/java/cluster/src/test/java/org/apache/qpid/server/cluster/SimpleClusterTest.java b/java/cluster/src/test/java/org/apache/qpid/server/cluster/SimpleClusterTest.java
index c427285f4a..70209cd2a3 100644
--- a/java/cluster/src/test/java/org/apache/qpid/server/cluster/SimpleClusterTest.java
+++ b/java/cluster/src/test/java/org/apache/qpid/server/cluster/SimpleClusterTest.java
@@ -21,6 +21,7 @@
package org.apache.qpid.server.cluster;
import org.apache.qpid.AMQException;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.url.URLSyntaxException;
import org.apache.qpid.client.AMQConnection;
import org.apache.qpid.client.AMQSession;
@@ -36,7 +37,7 @@ public class SimpleClusterTest extends TestCase
AMQConnection con = new AMQConnection("localhost:9000", "guest", "guest", "test", "/test");
AMQSession session = (AMQSession) con.createSession(false, AMQSession.NO_ACKNOWLEDGE);
System.out.println("Session created");
- session.declareExchange("my_exchange", "direct");
+ session.declareExchange(new AMQShortString("my_exchange"), new AMQShortString("direct"));
System.out.println("Exchange declared");
con.close();
System.out.println("Connection closed");
diff --git a/java/common/pom.xml b/java/common/pom.xml
index dc0db7f954..7472b5ef7d 100644
--- a/java/common/pom.xml
+++ b/java/common/pom.xml
@@ -68,21 +68,39 @@
</build>
<dependencies>
+
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</dependency>
+
+
+<!-- This is a mina dependency but it isn't being picked up-->
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-simple</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.mina</groupId>
+ <artifactId>mina-java5</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.mina</groupId>
+ <artifactId>mina-filter-ssl</artifactId>
+ </dependency>
+
<dependency>
<groupId>org.apache.mina</groupId>
<artifactId>mina-core</artifactId>
</dependency>
- <dependency>
+
+ <dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
+ <scope>test</scope>
</dependency>
- <dependency>
- <groupId>org.apache.geronimo.specs</groupId>
- <artifactId>geronimo-jms_1.1_spec</artifactId>
- </dependency>
+
</dependencies>
</project>
diff --git a/java/common/src/main/java/org/apache/qpid/AMQChannelException.java b/java/common/src/main/java/org/apache/qpid/AMQChannelException.java
index 996ac23b09..503f92b15d 100644
--- a/java/common/src/main/java/org/apache/qpid/AMQChannelException.java
+++ b/java/common/src/main/java/org/apache/qpid/AMQChannelException.java
@@ -22,6 +22,7 @@ package org.apache.qpid;
import org.apache.qpid.framing.ChannelCloseBody;
import org.apache.qpid.framing.AMQMethodBody;
+import org.apache.qpid.framing.AMQShortString;
public class AMQChannelException extends AMQException
{
@@ -51,6 +52,6 @@ public class AMQChannelException extends AMQException
public AMQMethodBody getCloseMethodBody()
{
- return ChannelCloseBody.createMethodBody(major, minor, _classId, _methodId, getErrorCode(), getMessage());
+ return ChannelCloseBody.createMethodBody(major, minor, _classId, _methodId, getErrorCode(), new AMQShortString(getMessage()));
}
}
diff --git a/java/common/src/main/java/org/apache/qpid/AMQConnectionException.java b/java/common/src/main/java/org/apache/qpid/AMQConnectionException.java
index 93754dbee9..c4772624e9 100644
--- a/java/common/src/main/java/org/apache/qpid/AMQConnectionException.java
+++ b/java/common/src/main/java/org/apache/qpid/AMQConnectionException.java
@@ -21,6 +21,7 @@
package org.apache.qpid;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.framing.ConnectionCloseBody;
public class AMQConnectionException extends AMQException
@@ -30,6 +31,7 @@ public class AMQConnectionException extends AMQException
/* AMQP version for which exception ocurred */
private final byte major;
private final byte minor;
+ boolean _closeConnetion;
public AMQConnectionException(int errorCode, String msg, int classId, int methodId, byte major, byte minor, Throwable t)
{
@@ -51,7 +53,7 @@ public class AMQConnectionException extends AMQException
public ConnectionCloseBody getCloseMethodBody()
{
- return ConnectionCloseBody.createMethodBody(major, minor, _classId, _methodId, getErrorCode(), getMessage());
+ return ConnectionCloseBody.createMethodBody(major, minor, _classId, _methodId, getErrorCode(), new AMQShortString(getMessage()));
}
public int getClassId()
@@ -62,5 +64,4 @@ public class AMQConnectionException extends AMQException
public int getMethodId(){
return _methodId;
}
-
}
diff --git a/java/common/src/main/java/org/apache/qpid/AMQConnectionFailureException.java b/java/common/src/main/java/org/apache/qpid/AMQConnectionFailureException.java
index 0979598cdb..2406312846 100644
--- a/java/common/src/main/java/org/apache/qpid/AMQConnectionFailureException.java
+++ b/java/common/src/main/java/org/apache/qpid/AMQConnectionFailureException.java
@@ -1,3 +1,23 @@
+/*
+ *
+ * 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;
public class AMQConnectionFailureException extends AMQException
diff --git a/java/broker/src/main/java/org/apache/qpid/server/message/MessageDecorator.java b/java/common/src/main/java/org/apache/qpid/AMQTimeoutException.java
index aba3b88a59..6af681f479 100644
--- a/java/broker/src/main/java/org/apache/qpid/server/message/MessageDecorator.java
+++ b/java/common/src/main/java/org/apache/qpid/AMQTimeoutException.java
@@ -18,8 +18,12 @@
*
*
*/
-package org.apache.qpid.server.message;
+package org.apache.qpid;
-public interface MessageDecorator
+public class AMQTimeoutException extends AMQException
{
+ public AMQTimeoutException(String message)
+ {
+ super(message);
+ }
}
diff --git a/java/common/src/main/java/org/apache/qpid/AMQUnknownExchangeType.java b/java/common/src/main/java/org/apache/qpid/AMQUnknownExchangeType.java
index 70f333a580..81deb91cdc 100644
--- a/java/common/src/main/java/org/apache/qpid/AMQUnknownExchangeType.java
+++ b/java/common/src/main/java/org/apache/qpid/AMQUnknownExchangeType.java
@@ -1,3 +1,23 @@
+/*
+ *
+ * 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;
public class AMQUnknownExchangeType extends AMQException
diff --git a/java/common/src/main/java/org/apache/qpid/common/AMQPFilterTypes.java b/java/common/src/main/java/org/apache/qpid/common/AMQPFilterTypes.java
index 56219755a3..d8aa9bf5ca 100644
--- a/java/common/src/main/java/org/apache/qpid/common/AMQPFilterTypes.java
+++ b/java/common/src/main/java/org/apache/qpid/common/AMQPFilterTypes.java
@@ -20,20 +20,22 @@
*/
package org.apache.qpid.common;
+import org.apache.qpid.framing.AMQShortString;
+
public enum AMQPFilterTypes
{
JMS_SELECTOR("x-filter-jms-selector"),
NO_CONSUME("x-filter-no-consume"),
AUTO_CLOSE("x-filter-auto-close");
- private final String _value;
+ private final AMQShortString _value;
AMQPFilterTypes(String value)
{
- _value = value;
+ _value = new AMQShortString(value);
}
- public String getValue()
+ public AMQShortString getValue()
{
return _value;
}
diff --git a/java/common/src/main/java/org/apache/qpid/exchange/ExchangeDefaults.java b/java/common/src/main/java/org/apache/qpid/exchange/ExchangeDefaults.java
index dca8075f7f..899261ef25 100644
--- a/java/common/src/main/java/org/apache/qpid/exchange/ExchangeDefaults.java
+++ b/java/common/src/main/java/org/apache/qpid/exchange/ExchangeDefaults.java
@@ -20,21 +20,28 @@
*/
package org.apache.qpid.exchange;
+import org.apache.qpid.framing.AMQShortString;
+
public class ExchangeDefaults
{
- public final static String TOPIC_EXCHANGE_NAME = "amq.topic";
+ public final static AMQShortString TOPIC_EXCHANGE_NAME = new AMQShortString("amq.topic");
+
+ public final static AMQShortString TOPIC_EXCHANGE_CLASS = new AMQShortString("topic");
+
+ public final static AMQShortString DIRECT_EXCHANGE_NAME = new AMQShortString("amq.direct");
+
+ public final static AMQShortString DIRECT_EXCHANGE_CLASS = new AMQShortString("direct");
- public final static String TOPIC_EXCHANGE_CLASS = "topic";
+ public final static AMQShortString HEADERS_EXCHANGE_NAME = new AMQShortString("amq.match");
- public final static String DIRECT_EXCHANGE_NAME = "amq.direct";
+ public final static AMQShortString HEADERS_EXCHANGE_CLASS = new AMQShortString("headers");
- public final static String DIRECT_EXCHANGE_CLASS = "direct";
+ public final static AMQShortString FANOUT_EXCHANGE_NAME = new AMQShortString("amq.fanout");
- public final static String HEADERS_EXCHANGE_NAME = "amq.match";
+ public final static AMQShortString FANOUT_EXCHANGE_CLASS = new AMQShortString("fanout");
- public final static String HEADERS_EXCHANGE_CLASS = "headers";
- public final static String FANOUT_EXCHANGE_NAME = "amq.fanout";
+ public final static AMQShortString SYSTEM_MANAGEMENT_EXCHANGE_NAME = new AMQShortString("qpid.sysmgmt");
- public final static String FANOUT_EXCHANGE_CLASS = "fanout";
+ public final static AMQShortString SYSTEM_MANAGEMENT_CLASS = new AMQShortString("sysmmgmt");
}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/AMQBody.java b/java/common/src/main/java/org/apache/qpid/framing/AMQBody.java
index 36287d2923..ebeea8d2b4 100644
--- a/java/common/src/main/java/org/apache/qpid/framing/AMQBody.java
+++ b/java/common/src/main/java/org/apache/qpid/framing/AMQBody.java
@@ -24,7 +24,7 @@ import org.apache.mina.common.ByteBuffer;
public abstract class AMQBody
{
- protected abstract byte getFrameType();
+ public abstract byte getFrameType();
/**
* Get the size of the body
diff --git a/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockDecoder.java b/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockDecoder.java
index 62699331e9..5e566a5fe8 100644
--- a/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockDecoder.java
+++ b/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockDecoder.java
@@ -24,93 +24,84 @@ import org.apache.log4j.Logger;
import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.IoSession;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
+import org.apache.qpid.protocol.AMQVersionAwareProtocolSession;
import java.util.HashMap;
import java.util.Map;
public class AMQDataBlockDecoder
{
- Logger _logger = Logger.getLogger(AMQDataBlockDecoder.class);
+ private static final String SESSION_METHOD_BODY_FACTORY = "QPID_SESSION_METHOD_BODY_FACTORY";
- private final Map _supportedBodies = new HashMap();
+ private static final BodyFactory[] _bodiesSupported = new BodyFactory[Byte.MAX_VALUE];
+
+ static
+ {
+ _bodiesSupported[HeartbeatBody.TYPE] = new HeartbeatBodyFactory();
+ }
+
+ Logger _logger = Logger.getLogger(AMQDataBlockDecoder.class);
public AMQDataBlockDecoder()
{
- _supportedBodies.put(new Byte(AMQRequestBody.TYPE), new BodyFactory() {
- public AMQBody createBody(ByteBuffer in) {
- return new AMQRequestBody();
- }
- });
- _supportedBodies.put(new Byte(AMQResponseBody.TYPE), new BodyFactory() {
- public AMQBody createBody(ByteBuffer in) {
- return new AMQResponseBody();
- }
- });
- _supportedBodies.put(new Byte(HeartbeatBody.TYPE), new HeartbeatBodyFactory());
}
public boolean decodable(IoSession session, ByteBuffer in) throws AMQFrameDecodingException
{
- // type, channel, body size and end byte
- if (in.remaining() < (1 + 2 + 4 + 1))
+ final int remainingAfterAttributes = in.remaining() - (1 + 2 + 4 + 1);
+ // type, channel, body length and end byte
+ if (remainingAfterAttributes < 0)
{
return false;
}
-
- final byte type = in.get();
- final int channel = in.getUnsignedShort();
+ in.skip(1 + 2);
final long bodySize = in.getUnsignedInt();
- // bodySize can be zero
- if (type <= 0 || channel < 0 || bodySize < 0)
+ return (remainingAfterAttributes >= bodySize);
+ }
+
+
+ protected Object createAndPopulateFrame(IoSession session, ByteBuffer in)
+ throws AMQFrameDecodingException, AMQProtocolVersionException
+ {
+ final byte type = in.get();
+ BodyFactory bodyFactory;
+ if (type == AMQRequestBody.TYPE)
{
- throw new AMQFrameDecodingException("Undecodable frame: type = " + type + " channel = " + channel +
- " bodySize = " + bodySize);
+ AMQVersionAwareProtocolSession protocolSession = (AMQVersionAwareProtocolSession) session.getAttachment();
+ bodyFactory = new AMQRequestBodyFactory(protocolSession);
}
-
- if (in.remaining() < (bodySize + 1))
+ else if (type == AMQResponseBody.TYPE)
{
- return false;
+ AMQVersionAwareProtocolSession protocolSession = (AMQVersionAwareProtocolSession) session.getAttachment();
+ bodyFactory = new AMQResponseBodyFactory(protocolSession);
}
- return true;
- }
-
- private boolean isSupportedFrameType(byte frameType)
- {
- final boolean result = _supportedBodies.containsKey(new Byte(frameType));
-
- if (!result)
+ else
{
- _logger.warn("AMQDataBlockDecoder does not handle frame type " + frameType);
+ bodyFactory = _bodiesSupported[type];
}
- return result;
- }
-
- protected Object createAndPopulateFrame(ByteBuffer in)
- throws AMQFrameDecodingException, AMQProtocolVersionException
- {
- final byte type = in.get();
- if (!isSupportedFrameType(type))
+ if(bodyFactory == null)
{
throw new AMQFrameDecodingException("Unsupported frame type: " + type);
}
+
final int channel = in.getUnsignedShort();
final long bodySize = in.getUnsignedInt();
- BodyFactory bodyFactory = (BodyFactory) _supportedBodies.get(new Byte(type));
- if (bodyFactory == null)
+ // bodySize can be zero
+ if (channel < 0 || bodySize < 0)
{
- throw new AMQFrameDecodingException("Unsupported body type: " + type);
+ throw new AMQFrameDecodingException("Undecodable frame: type = " + type + " channel = " + channel +
+ " bodySize = " + bodySize);
}
- AMQFrame frame = new AMQFrame();
- frame.populateFromBuffer(in, channel, bodySize, bodyFactory);
+ AMQFrame frame = new AMQFrame(in, channel, bodySize, bodyFactory);
byte marker = in.get();
if ((marker & 0xFF) != 0xCE)
{
- throw new AMQFrameDecodingException("End of frame marker not found. Read " + marker + " size=" + bodySize + " type=" + type);
+ throw new AMQFrameDecodingException("End of frame marker not found. Read " + marker + " length=" + bodySize + " type=" + type);
}
return frame;
}
@@ -118,6 +109,6 @@ public class AMQDataBlockDecoder
public void decode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out)
throws Exception
{
- out.write(createAndPopulateFrame(in));
+ out.write(createAndPopulateFrame(session, in));
}
}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockEncoder.java b/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockEncoder.java
index 3446563d35..478cdeb406 100644
--- a/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockEncoder.java
+++ b/java/common/src/main/java/org/apache/qpid/framing/AMQDataBlockEncoder.java
@@ -28,17 +28,16 @@ import org.apache.mina.filter.codec.demux.MessageEncoder;
import java.util.HashSet;
import java.util.Set;
+import java.util.Collections;
-public class AMQDataBlockEncoder implements MessageEncoder
+public final class AMQDataBlockEncoder implements MessageEncoder
{
- Logger _logger = Logger.getLogger(AMQDataBlockEncoder.class);
+ private static final Logger _logger = Logger.getLogger(AMQDataBlockEncoder.class);
- private Set _messageTypes;
+ private final Set _messageTypes = Collections.singleton(EncodableAMQDataBlock.class);
public AMQDataBlockEncoder()
{
- _messageTypes = new HashSet();
- _messageTypes.add(EncodableAMQDataBlock.class);
}
public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception
diff --git a/java/common/src/main/java/org/apache/qpid/framing/AMQFrame.java b/java/common/src/main/java/org/apache/qpid/framing/AMQFrame.java
index 6af691fbe8..11f505fd4b 100644
--- a/java/common/src/main/java/org/apache/qpid/framing/AMQFrame.java
+++ b/java/common/src/main/java/org/apache/qpid/framing/AMQFrame.java
@@ -24,53 +24,52 @@ import org.apache.mina.common.ByteBuffer;
public class AMQFrame extends AMQDataBlock implements EncodableAMQDataBlock
{
- public int channel;
+ private final int _channel;
- public AMQBody bodyFrame;
+ private final AMQBody _bodyFrame;
- public AMQFrame()
+
+
+ public AMQFrame(final int channel, final AMQBody bodyFrame)
{
+ _channel = channel;
+ _bodyFrame = bodyFrame;
}
- public AMQFrame(int channel, AMQBody bodyFrame)
+ public AMQFrame(final ByteBuffer in, final int channel, final long bodySize, final BodyFactory bodyFactory) throws AMQFrameDecodingException
{
- this.channel = channel;
- this.bodyFrame = bodyFrame;
+ this._channel = channel;
+ this._bodyFrame = bodyFactory.createBody(in,bodySize);
}
public long getSize()
{
- return 1 + 2 + 4 + bodyFrame.getSize() + 1;
+ return 1 + 2 + 4 + _bodyFrame.getSize() + 1;
}
public void writePayload(ByteBuffer buffer)
{
- buffer.put(bodyFrame.getFrameType());
- // TODO: how does channel get populated
- EncodingUtils.writeUnsignedShort(buffer, channel);
- EncodingUtils.writeUnsignedInteger(buffer, bodyFrame.getSize());
- bodyFrame.writePayload(buffer);
+ buffer.put(_bodyFrame.getFrameType());
+ EncodingUtils.writeUnsignedShort(buffer, _channel);
+ EncodingUtils.writeUnsignedInteger(buffer, _bodyFrame.getSize());
+ _bodyFrame.writePayload(buffer);
buffer.put((byte) 0xCE);
}
- /**
- *
- * @param buffer
- * @param channel unsigned short
- * @param bodySize unsigned integer
- * @param bodyFactory
- * @throws AMQFrameDecodingException
- */
- public void populateFromBuffer(ByteBuffer buffer, int channel, long bodySize, BodyFactory bodyFactory)
- throws AMQFrameDecodingException, AMQProtocolVersionException
+ public final int getChannel()
{
- this.channel = channel;
- bodyFrame = bodyFactory.createBody(buffer);
- bodyFrame.populateFromBuffer(buffer, bodySize);
+ return _channel;
}
+ public final AMQBody getBodyFrame()
+ {
+ return _bodyFrame;
+ }
+
+
+
public String toString()
{
- return "Frame channelId: " + channel + ", bodyFrame: " + String.valueOf(bodyFrame);
+ return "Frame channelId: " + _channel + ", bodyFrame: " + String.valueOf(_bodyFrame);
}
}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBody.java b/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBody.java
index e140a9b334..ccd1ef32b8 100644
--- a/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBody.java
+++ b/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBody.java
@@ -57,7 +57,7 @@ public abstract class AMQMethodBody extends AMQBody
protected abstract void writeMethodPayload(ByteBuffer buffer);
- protected byte getFrameType()
+ public byte getFrameType()
{
return TYPE;
}
@@ -110,10 +110,9 @@ public abstract class AMQMethodBody extends AMQBody
return new AMQConnectionException(code, message, getClazz(), getMethod(), major, minor);
}
-
-
public AMQConnectionException getConnectionException(int code, String message, Throwable cause)
{
return new AMQConnectionException(code, message, getClazz(), getMethod(), major, minor, cause);
}
+
}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyFactory.java b/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyFactory.java
index 3dcbe926fe..6067e2fce5 100644
--- a/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyFactory.java
+++ b/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyFactory.java
@@ -22,30 +22,21 @@ package org.apache.qpid.framing;
import org.apache.log4j.Logger;
import org.apache.mina.common.ByteBuffer;
+import org.apache.qpid.protocol.AMQVersionAwareProtocolSession;
public class AMQMethodBodyFactory implements BodyFactory
{
private static final Logger _log = Logger.getLogger(AMQMethodBodyFactory.class);
+
+ private final AMQVersionAwareProtocolSession _protocolSession;
- private static final AMQMethodBodyFactory _instance = new AMQMethodBodyFactory();
-
- public static AMQMethodBodyFactory getInstance()
- {
- return _instance;
- }
-
- private AMQMethodBodyFactory()
+ public AMQMethodBodyFactory(AMQVersionAwareProtocolSession protocolSession)
{
- _log.debug("Creating method body factory");
+ _protocolSession = protocolSession;
}
- public AMQMethodBody createBody(ByteBuffer in) throws AMQFrameDecodingException
+ public AMQMethodBody createBody(ByteBuffer in, long bodySize) throws AMQFrameDecodingException
{
- // AMQP version change: MethodBodyDecoderRegistry is obsolete, since all the XML
- // segments generated together are now handled by MainRegistry. The Cluster class,
- // if generated together with amqp.xml is a part of MainRegistry.
- // TODO: Connect with version acquired from ProtocolInitiation class.
- return MainRegistry.get((short)in.getUnsignedShort(), (short)in.getUnsignedShort(),
- (byte)0, (byte)9);
+ return _protocolSession.getRegistry().get((short)in.getUnsignedShort(), (short)in.getUnsignedShort(), in, bodySize);
}
}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyInstanceFactory.java b/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyInstanceFactory.java
new file mode 100644
index 0000000000..5309a80bdb
--- /dev/null
+++ b/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBodyInstanceFactory.java
@@ -0,0 +1,30 @@
+/*
+ *
+ * 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.framing;
+
+import org.apache.mina.common.ByteBuffer;
+
+
+public abstract interface AMQMethodBodyInstanceFactory
+{
+ public AMQMethodBody newInstance(byte major, byte minor, ByteBuffer buffer, long size) throws AMQFrameDecodingException;
+ public AMQMethodBody newInstance(byte major, byte minor, int clazzID, int methodID, ByteBuffer buffer, long size) throws AMQFrameDecodingException;
+}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/AMQRequestBody.java b/java/common/src/main/java/org/apache/qpid/framing/AMQRequestBody.java
index 6df7dff27b..3bc16601b6 100644
--- a/java/common/src/main/java/org/apache/qpid/framing/AMQRequestBody.java
+++ b/java/common/src/main/java/org/apache/qpid/framing/AMQRequestBody.java
@@ -21,6 +21,7 @@
package org.apache.qpid.framing;
import org.apache.mina.common.ByteBuffer;
+import org.apache.qpid.protocol.AMQVersionAwareProtocolSession;
public class AMQRequestBody extends AMQBody
{
@@ -30,16 +31,21 @@ public class AMQRequestBody extends AMQBody
protected long requestId;
protected long responseMark;
protected AMQMethodBody methodPayload;
-
+ protected AMQVersionAwareProtocolSession protocolSession;
// Constructor
- public AMQRequestBody() {}
+ public AMQRequestBody(AMQVersionAwareProtocolSession protocolSession)
+ {
+ this.protocolSession = protocolSession;
+ }
+
public AMQRequestBody(long requestId, long responseMark,
AMQMethodBody methodPayload)
{
this.requestId = requestId;
this.responseMark = responseMark;
this.methodPayload = methodPayload;
+ protocolSession = null;
}
@@ -49,7 +55,7 @@ public class AMQRequestBody extends AMQBody
public AMQMethodBody getMethodPayload() { return methodPayload; }
- protected byte getFrameType()
+ public byte getFrameType()
{
return TYPE;
}
@@ -68,14 +74,19 @@ public class AMQRequestBody extends AMQBody
}
protected void populateFromBuffer(ByteBuffer buffer, long size)
- throws AMQFrameDecodingException, AMQProtocolVersionException
+ throws AMQFrameDecodingException
{
+ if (protocolSession == null)
+ {
+ throw new AMQFrameDecodingException("Cannot call populateFromBuffer() without using correct constructor.");
+ }
+
requestId = EncodingUtils.readLong(buffer);
responseMark = EncodingUtils.readLong(buffer);
int reserved = EncodingUtils.readInteger(buffer); // reserved, throw away
- AMQMethodBodyFactory factory = AMQMethodBodyFactory.getInstance();
- methodPayload = factory.createBody(buffer);
- methodPayload.populateFromBuffer(buffer, size - 8 - 8 - 4);
+
+ AMQMethodBodyFactory methodBodyFactory = new AMQMethodBodyFactory(protocolSession);
+ methodPayload = methodBodyFactory.createBody(buffer, size);
}
public String toString()
@@ -89,9 +100,6 @@ public class AMQRequestBody extends AMQBody
{
AMQRequestBody requestFrame = new AMQRequestBody(requestId, responseMark,
methodPayload);
- AMQFrame frame = new AMQFrame();
- frame.channel = channelId;
- frame.bodyFrame = requestFrame;
- return frame;
+ return new AMQFrame(channelId, requestFrame);
}
}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/AMQRequestBodyFactory.java b/java/common/src/main/java/org/apache/qpid/framing/AMQRequestBodyFactory.java
new file mode 100644
index 0000000000..9d47ccd68e
--- /dev/null
+++ b/java/common/src/main/java/org/apache/qpid/framing/AMQRequestBodyFactory.java
@@ -0,0 +1,41 @@
+/*
+ *
+ * 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.framing;
+
+import org.apache.mina.common.ByteBuffer;
+import org.apache.qpid.protocol.AMQVersionAwareProtocolSession;
+
+public class AMQRequestBodyFactory implements BodyFactory
+{
+ private final AMQVersionAwareProtocolSession protocolSession;
+
+ public AMQRequestBodyFactory(AMQVersionAwareProtocolSession protocolSession)
+ {
+ this.protocolSession = protocolSession;
+ }
+
+ public AMQBody createBody(ByteBuffer in, long bodySize) throws AMQFrameDecodingException
+ {
+ AMQRequestBody rb = new AMQRequestBody(protocolSession);
+ rb.populateFromBuffer(in, bodySize);
+ return rb;
+ }
+}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/AMQResponseBody.java b/java/common/src/main/java/org/apache/qpid/framing/AMQResponseBody.java
index c7aee6ac92..7b35aaeb86 100644
--- a/java/common/src/main/java/org/apache/qpid/framing/AMQResponseBody.java
+++ b/java/common/src/main/java/org/apache/qpid/framing/AMQResponseBody.java
@@ -21,6 +21,7 @@
package org.apache.qpid.framing;
import org.apache.mina.common.ByteBuffer;
+import org.apache.qpid.protocol.AMQVersionAwareProtocolSession;
public class AMQResponseBody extends AMQBody
{
@@ -31,9 +32,14 @@ public class AMQResponseBody extends AMQBody
protected long requestId;
protected int batchOffset;
protected AMQMethodBody methodPayload;
+ protected AMQVersionAwareProtocolSession protocolSession;
// Constructor
- public AMQResponseBody() {}
+ public AMQResponseBody(AMQVersionAwareProtocolSession protocolSession)
+ {
+ this.protocolSession = protocolSession;
+ }
+
public AMQResponseBody(long responseId, long requestId,
int batchOffset, AMQMethodBody methodPayload)
{
@@ -41,6 +47,7 @@ public class AMQResponseBody extends AMQBody
this.requestId = requestId;
this.batchOffset = batchOffset;
this.methodPayload = methodPayload;
+ protocolSession = null;
}
// Field methods
@@ -49,7 +56,7 @@ public class AMQResponseBody extends AMQBody
public int getBatchOffset() { return batchOffset; }
public AMQMethodBody getMethodPayload() { return methodPayload; }
- protected byte getFrameType()
+ public byte getFrameType()
{
return TYPE;
}
@@ -69,15 +76,18 @@ public class AMQResponseBody extends AMQBody
}
protected void populateFromBuffer(ByteBuffer buffer, long size)
- throws AMQFrameDecodingException, AMQProtocolVersionException
+ throws AMQFrameDecodingException
{
+ if (protocolSession == null)
+ throw new AMQFrameDecodingException("Cannot call populateFromBuffer() without using correct constructor.");
+
responseId = EncodingUtils.readLong(buffer);
requestId = EncodingUtils.readLong(buffer);
// XXX
batchOffset = EncodingUtils.readInteger(buffer);
- AMQMethodBodyFactory factory = AMQMethodBodyFactory.getInstance();
- methodPayload = factory.createBody(buffer);
- methodPayload.populateFromBuffer(buffer, size - 8 - 8 - 4);
+
+ AMQMethodBodyFactory methodBodyFactory = new AMQMethodBodyFactory(protocolSession);
+ methodPayload = methodBodyFactory.createBody(buffer, size);
}
public String toString()
@@ -91,9 +101,6 @@ public class AMQResponseBody extends AMQBody
{
AMQResponseBody responseFrame = new AMQResponseBody(responseId,
requestId, batchOffset, methodPayload);
- AMQFrame frame = new AMQFrame();
- frame.channel = channelId;
- frame.bodyFrame = responseFrame;
- return frame;
+ return new AMQFrame(channelId, responseFrame);
}
}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/AMQResponseBodyFactory.java b/java/common/src/main/java/org/apache/qpid/framing/AMQResponseBodyFactory.java
new file mode 100644
index 0000000000..4209aad11f
--- /dev/null
+++ b/java/common/src/main/java/org/apache/qpid/framing/AMQResponseBodyFactory.java
@@ -0,0 +1,41 @@
+/*
+ *
+ * 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.framing;
+
+import org.apache.mina.common.ByteBuffer;
+import org.apache.qpid.protocol.AMQVersionAwareProtocolSession;
+
+public class AMQResponseBodyFactory implements BodyFactory
+{
+ private final AMQVersionAwareProtocolSession protocolSession;
+
+ public AMQResponseBodyFactory(AMQVersionAwareProtocolSession protocolSession)
+ {
+ this.protocolSession = protocolSession;
+ }
+
+ public AMQBody createBody(ByteBuffer in, long bodySize) throws AMQFrameDecodingException
+ {
+ AMQResponseBody rb = new AMQResponseBody(protocolSession);
+ rb.populateFromBuffer(in, bodySize);
+ return rb;
+ }
+}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/AMQShortString.java b/java/common/src/main/java/org/apache/qpid/framing/AMQShortString.java
new file mode 100644
index 0000000000..f98a62751c
--- /dev/null
+++ b/java/common/src/main/java/org/apache/qpid/framing/AMQShortString.java
@@ -0,0 +1,374 @@
+/*
+ *
+ * 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.framing;
+
+import org.apache.mina.common.ByteBuffer;
+import org.apache.log4j.Logger;
+
+import java.util.Arrays;
+
+/**
+ * A short string is a representation of an AMQ Short String
+ * Short strings differ from the Java String class by being limited to on ASCII characters (0-127)
+ * and thus can be held more effectively in a byte buffer.
+ *
+ */
+public final class AMQShortString implements CharSequence
+{
+ private static final Logger _logger = Logger.getLogger(AMQShortString.class);
+
+ private final ByteBuffer _data;
+ private int _hashCode;
+ private static final char[] EMPTY_CHAR_ARRAY = new char[0];
+
+ public AMQShortString(byte[] data)
+ {
+
+ _data = ByteBuffer.wrap(data);
+ }
+
+
+ public AMQShortString(String data)
+ {
+ this(data == null ? EMPTY_CHAR_ARRAY : data.toCharArray());
+ if(data != null) _hashCode = data.hashCode();
+ }
+
+ public AMQShortString(char[] data)
+ {
+ if(data == null)
+ {
+ throw new NullPointerException("Cannot create AMQShortString with null char[]");
+ }
+ final int length = data.length;
+ final byte[] stringBytes = new byte[length];
+ for(int i = 0; i < length; i++)
+ {
+ stringBytes[i] = (byte) (0xFF & data[i]);
+ }
+
+ _data = ByteBuffer.wrap(stringBytes);
+ _data.rewind();
+
+ }
+
+ public AMQShortString(CharSequence charSequence)
+ {
+ final int length = charSequence.length();
+ final byte[] stringBytes = new byte[length];
+ int hash = 0;
+ for(int i = 0 ; i < length; i++)
+ {
+ stringBytes[i] = ((byte) (0xFF & charSequence.charAt(i)));
+ hash = (31 * hash) + stringBytes[i];
+
+ }
+ _data = ByteBuffer.wrap(stringBytes);
+ _data.rewind();
+ _hashCode = hash;
+
+ }
+
+ private AMQShortString(ByteBuffer data)
+ {
+ _data = data;
+
+ }
+
+
+ /**
+ * Get the length of the short string
+ * @return length of the underlying byte array
+ */
+ public int length()
+ {
+ return _data.limit();
+ }
+
+ public char charAt(int index)
+ {
+
+ return (char) _data.get(index);
+
+ }
+
+ public CharSequence subSequence(int start, int end)
+ {
+ return new CharSubSequence(start,end);
+ }
+
+ public int writeToByteArray(byte[] encoding, int pos)
+ {
+ final int size = length();
+ encoding[pos++] = (byte) length();
+ for(int i = 0; i < size; i++)
+ {
+ encoding[pos++] = _data.get(i);
+ }
+ return pos;
+ }
+
+ public static AMQShortString readFromByteArray(byte[] byteEncodedDestination, int pos)
+ {
+
+ final byte len = byteEncodedDestination[pos];
+ if(len == 0)
+ {
+ return null;
+ }
+ ByteBuffer data = ByteBuffer.wrap(byteEncodedDestination,pos+1,len).slice();
+
+
+ return new AMQShortString(data);
+ }
+
+ public static AMQShortString readFromBuffer(ByteBuffer buffer)
+ {
+ final short length = buffer.getUnsigned();
+ if (length == 0)
+ {
+ return null;
+ }
+ else
+ {
+ ByteBuffer data = buffer.slice();
+ data.limit(length);
+ data.rewind();
+ buffer.skip(length);
+
+ return new AMQShortString(data);
+ }
+ }
+
+
+ public byte[] getBytes()
+ {
+
+ if(_data.buf().hasArray() && _data.arrayOffset() == 0)
+ {
+ return _data.array();
+ }
+ else
+ {
+ final int size = length();
+ byte[] b = new byte[size];
+ ByteBuffer buf = _data.duplicate();
+ buf.rewind();
+ buf.get(b);
+
+
+ return b;
+ }
+
+
+ }
+
+ public void writeToBuffer(ByteBuffer buffer)
+ {
+
+
+ final int size = length();
+ if (size != 0)
+ {
+
+ buffer.put((byte)size);
+ if(_data.buf().hasArray())
+ {
+ buffer.put(_data.array(),_data.arrayOffset(),length());
+ }
+ else
+ {
+
+ for(int i = 0; i < size; i++)
+ {
+
+ buffer.put(_data.get(i));
+ }
+ }
+ }
+ else
+ {
+ // really writing out unsigned byte
+ buffer.put((byte) 0);
+ }
+
+ }
+
+ private final class CharSubSequence implements CharSequence
+ {
+ private final int _offset;
+ private final int _end;
+
+
+ public CharSubSequence(final int offset, final int end)
+ {
+ _offset = offset;
+ _end = end;
+ }
+
+
+ public int length()
+ {
+ return _end - _offset;
+ }
+
+ public char charAt(int index)
+ {
+ return AMQShortString.this.charAt(index + _offset);
+ }
+
+ public CharSequence subSequence(int start, int end)
+ {
+ return new CharSubSequence(start+_offset,end+_offset);
+ }
+ }
+
+
+
+ public char[] asChars()
+ {
+ final int size = length();
+ final char[] chars = new char[size];
+
+
+
+
+ for(int i = 0 ; i < size; i++)
+ {
+ chars[i] = (char) _data.get(i);
+ }
+ return chars;
+ }
+
+
+
+ public String asString()
+ {
+ return new String(asChars());
+ }
+
+ public boolean equals(Object o)
+ {
+ if(o == null)
+ {
+ return false;
+ }
+ if(o == this)
+ {
+ return true;
+ }
+ if(o instanceof AMQShortString)
+ {
+
+ final AMQShortString otherString = (AMQShortString) o;
+
+ if((_hashCode != 0) && (otherString._hashCode != 0) && (_hashCode != otherString._hashCode))
+ {
+ return false;
+ }
+
+ return _data.equals(otherString._data);
+
+
+
+
+ }
+ return (o instanceof CharSequence) && equals((CharSequence)o);
+
+ }
+
+ public boolean equals(CharSequence s)
+ {
+ if(s == null)
+ {
+ return false;
+ }
+ if(s.length() != length())
+ {
+ return false;
+ }
+ for(int i = 0; i < length(); i++)
+ {
+ if(charAt(i)!= s.charAt(i))
+ {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ public int hashCode()
+ {
+ int hash = _hashCode;
+ if(hash == 0)
+ {
+ final int size = length();
+
+
+ for(int i = 0; i < size; i++)
+ {
+ hash = (31 * hash) + _data.get(i);
+ }
+ _hashCode = hash;
+ }
+
+ return hash;
+ }
+
+ public void setDirty()
+ {
+ _hashCode = 0;
+ }
+
+ public String toString()
+ {
+ return asString();
+ }
+
+
+ public int compareTo(AMQShortString name)
+ {
+ if(name == null)
+ {
+ return 1;
+ }
+ else
+ {
+
+ if(name.length() < length())
+ {
+ return - name.compareTo(this);
+ }
+
+
+
+ for(int i = 0; i < length() ; i++)
+ {
+ final byte d = _data.get(i);
+ final byte n = name._data.get(i);
+ if(d < n) return -1;
+ if(d > n) return 1;
+ }
+
+ return length() == name.length() ? 0 : -1;
+ }
+ }
+}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/AMQType.java b/java/common/src/main/java/org/apache/qpid/framing/AMQType.java
index 23c1929205..5175eace1e 100644
--- a/java/common/src/main/java/org/apache/qpid/framing/AMQType.java
+++ b/java/common/src/main/java/org/apache/qpid/framing/AMQType.java
@@ -230,7 +230,7 @@ public enum AMQType
{
public int getEncodingSize(Object value)
{
- return 1 + (value == null ? 0 : ((byte[]) value).length);
+ return EncodingUtils.encodedLongstrLength((byte[]) value);
}
@@ -250,12 +250,12 @@ public enum AMQType
public void writeValueImpl(Object value, ByteBuffer buffer)
{
- EncodingUtils.writeBytes(buffer, (byte[]) value);
+ EncodingUtils.writeLongstr(buffer, (byte[]) value);
}
public Object readValueFromBuffer(ByteBuffer buffer)
{
- return EncodingUtils.readBytes(buffer);
+ return EncodingUtils.readLongstr(buffer);
}
},
diff --git a/java/common/src/main/java/org/apache/qpid/framing/AMQTypedValue.java b/java/common/src/main/java/org/apache/qpid/framing/AMQTypedValue.java
index b29c23c2a2..efdd903f1f 100644
--- a/java/common/src/main/java/org/apache/qpid/framing/AMQTypedValue.java
+++ b/java/common/src/main/java/org/apache/qpid/framing/AMQTypedValue.java
@@ -1,3 +1,23 @@
+/*
+ *
+ * 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.framing;
import org.apache.mina.common.ByteBuffer;
@@ -51,4 +71,9 @@ public class AMQTypedValue
AMQType type = AMQTypeMap.getType(buffer.get());
return new AMQTypedValue(type, buffer);
}
+
+ public String toString()
+ {
+ return "["+getType()+": "+getValue()+"]";
+ }
}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/BodyFactory.java b/java/common/src/main/java/org/apache/qpid/framing/BodyFactory.java
index cf5708d993..246e91f1fb 100644
--- a/java/common/src/main/java/org/apache/qpid/framing/BodyFactory.java
+++ b/java/common/src/main/java/org/apache/qpid/framing/BodyFactory.java
@@ -21,11 +21,12 @@
package org.apache.qpid.framing;
import org.apache.mina.common.ByteBuffer;
+import org.apache.qpid.protocol.AMQVersionAwareProtocolSession;
/**
* Any class that is capable of turning a stream of bytes into an AMQ structure must implement this interface.
*/
public interface BodyFactory
{
- AMQBody createBody(ByteBuffer in) throws AMQFrameDecodingException;
+ AMQBody createBody(ByteBuffer in, long bodySize) throws AMQFrameDecodingException;
}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/EncodingUtils.java b/java/common/src/main/java/org/apache/qpid/framing/EncodingUtils.java
index c88c5d3bd3..f31fa8097e 100644
--- a/java/common/src/main/java/org/apache/qpid/framing/EncodingUtils.java
+++ b/java/common/src/main/java/org/apache/qpid/framing/EncodingUtils.java
@@ -35,6 +35,7 @@ public class EncodingUtils
public static final int SIZEOF_UNSIGNED_SHORT = 2;
public static final int SIZEOF_UNSIGNED_INT = 4;
+ private static final boolean[] ALL_FALSE_ARRAY = new boolean[8];
public static int encodedShortStringLength(String s)
{
@@ -48,6 +49,120 @@ public class EncodingUtils
}
}
+
+ public static int encodedShortStringLength(short s)
+ {
+ if( s == 0 )
+ {
+ return 1 + 1;
+ }
+
+ int len = 0;
+ if(s < 0)
+ {
+ len=1;
+ // sloppy - doesn't work of Integer.MIN_VALUE
+ s=(short)-s;
+ }
+
+ if(s>9999)
+ {
+ return 1+5;
+ }
+ else if(s>999)
+ {
+ return 1+4;
+ }
+ else if(s>99)
+ {
+ return 1+3;
+ }
+ else if(s>9)
+ {
+ return 1+2;
+ }
+ else
+ {
+ return 1+1;
+ }
+
+ }
+
+
+ public static int encodedShortStringLength(int i)
+ {
+ if( i == 0 )
+ {
+ return 1 + 1;
+ }
+
+ int len = 0;
+ if(i < 0)
+ {
+ len=1;
+ // sloppy - doesn't work of Integer.MIN_VALUE
+ i=-i;
+ }
+
+ // range is now 1 - 2147483647
+ if(i < Short.MAX_VALUE)
+ {
+ return len + encodedShortStringLength((short)i);
+ }
+ else if (i > 999999)
+ {
+ return len + 6 + encodedShortStringLength((short)(i/1000000));
+ }
+ else // if (i > 99999)
+ {
+ return len + 5 + encodedShortStringLength((short)(i/100000));
+ }
+
+ }
+
+ public static int encodedShortStringLength(long l)
+ {
+ if(l == 0)
+ {
+ return 1 + 1;
+ }
+
+ int len = 0;
+ if(l < 0)
+ {
+ len=1;
+ // sloppy - doesn't work of Long.MIN_VALUE
+ l=-l;
+ }
+ if(l < Integer.MAX_VALUE)
+ {
+ return len + encodedShortStringLength((int) l);
+ }
+ else if(l > 9999999999L)
+ {
+ return len + 10 + encodedShortStringLength((int) (l / 10000000000L));
+ }
+ else
+ {
+ return len + 1 + encodedShortStringLength((int) (l / 10L));
+ }
+
+ }
+
+
+ public static int encodedShortStringLength(AMQShortString s)
+ {
+ if (s == null)
+ {
+ return 1;
+ }
+ else
+ {
+ return (short) (1 + s.length());
+ }
+ }
+
+
public static int encodedLongStringLength(String s)
{
if (s == null)
@@ -122,6 +237,21 @@ public class EncodingUtils
}
}
+
+ public static void writeShortStringBytes(ByteBuffer buffer, AMQShortString s)
+ {
+ if (s != null)
+ {
+
+ s.writeToBuffer(buffer);
+ }
+ else
+ {
+ // really writing out unsigned byte
+ buffer.put((byte) 0);
+ }
+ }
+
public static void writeLongStringBytes(ByteBuffer buffer, String s)
{
assert s == null || s.length() <= 0xFFFE;
@@ -224,6 +354,7 @@ public class EncodingUtils
}
}
+
public static void writeFieldTableBytes(ByteBuffer buffer, FieldTable table)
{
if (table != null)
@@ -255,6 +386,238 @@ public class EncodingUtils
buffer.put(packedValue);
}
+ public static void writeBooleans(ByteBuffer buffer, boolean value)
+ {
+
+ buffer.put(value ? (byte) 1 : (byte) 0);
+ }
+
+ public static void writeBooleans(ByteBuffer buffer, boolean value0, boolean value1)
+ {
+ byte packedValue = value0 ? (byte) 1 : (byte) 0;
+
+ if (value1)
+ {
+ packedValue = (byte) (packedValue | (byte)(1 << 1));
+ }
+
+
+ buffer.put(packedValue);
+ }
+
+ public static void writeBooleans(ByteBuffer buffer, boolean value0, boolean value1, boolean value2)
+ {
+ byte packedValue = value0 ? (byte) 1 : (byte) 0;
+
+ if (value1)
+ {
+ packedValue = (byte) (packedValue | (byte)(1 << 1));
+ }
+
+ if (value2)
+ {
+ packedValue = (byte) (packedValue | (byte)(1 << 2));
+ }
+
+
+ buffer.put(packedValue);
+ }
+
+
+
+ public static void writeBooleans(ByteBuffer buffer,
+ boolean value0,
+ boolean value1,
+ boolean value2,
+ boolean value3)
+ {
+ byte packedValue = value0 ? (byte) 1 : (byte) 0;
+
+ if (value1)
+ {
+ packedValue = (byte) (packedValue | (byte)(1 << 1));
+ }
+
+ if (value2)
+ {
+ packedValue = (byte) (packedValue | (byte)(1 << 2));
+ }
+
+ if (value3)
+ {
+ packedValue = (byte) (packedValue | (byte)(1 << 3));
+ }
+
+ buffer.put(packedValue);
+ }
+
+ public static void writeBooleans(ByteBuffer buffer,
+ boolean value0,
+ boolean value1,
+ boolean value2,
+ boolean value3,
+ boolean value4)
+ {
+ byte packedValue = value0 ? (byte) 1 : (byte) 0;
+
+ if (value1)
+ {
+ packedValue = (byte) (packedValue | (byte)(1 << 1));
+ }
+
+ if (value2)
+ {
+ packedValue = (byte) (packedValue | (byte)(1 << 2));
+ }
+
+ if (value3)
+ {
+ packedValue = (byte) (packedValue | (byte)(1 << 3));
+ }
+
+ if (value4)
+ {
+ packedValue = (byte) (packedValue | (byte)(1 << 4));
+ }
+
+ buffer.put(packedValue);
+ }
+
+ public static void writeBooleans(ByteBuffer buffer,
+ boolean value0,
+ boolean value1,
+ boolean value2,
+ boolean value3,
+ boolean value4,
+ boolean value5)
+ {
+ byte packedValue = value0 ? (byte) 1 : (byte) 0;
+
+ if (value1)
+ {
+ packedValue = (byte) (packedValue | (byte)(1 << 1));
+ }
+
+ if (value2)
+ {
+ packedValue = (byte) (packedValue | (byte)(1 << 2));
+ }
+
+ if (value3)
+ {
+ packedValue = (byte) (packedValue | (byte)(1 << 3));
+ }
+
+ if (value4)
+ {
+ packedValue = (byte) (packedValue | (byte)(1 << 4));
+ }
+
+ if (value5)
+ {
+ packedValue = (byte) (packedValue | (byte)(1 << 5));
+ }
+
+ buffer.put(packedValue);
+ }
+
+ public static void writeBooleans(ByteBuffer buffer,
+ boolean value0,
+ boolean value1,
+ boolean value2,
+ boolean value3,
+ boolean value4,
+ boolean value5,
+ boolean value6)
+ {
+ byte packedValue = value0 ? (byte) 1 : (byte) 0;
+
+ if (value1)
+ {
+ packedValue = (byte) (packedValue | (byte)(1 << 1));
+ }
+
+ if (value2)
+ {
+ packedValue = (byte) (packedValue | (byte)(1 << 2));
+ }
+
+ if (value3)
+ {
+ packedValue = (byte) (packedValue | (byte)(1 << 3));
+ }
+
+ if (value4)
+ {
+ packedValue = (byte) (packedValue | (byte)(1 << 4));
+ }
+
+ if (value5)
+ {
+ packedValue = (byte) (packedValue | (byte)(1 << 5));
+ }
+
+ if (value6)
+ {
+ packedValue = (byte) (packedValue | (byte)(1 << 6));
+ }
+
+ buffer.put(packedValue);
+ }
+
+ public static void writeBooleans(ByteBuffer buffer,
+ boolean value0,
+ boolean value1,
+ boolean value2,
+ boolean value3,
+ boolean value4,
+ boolean value5,
+ boolean value6,
+ boolean value7)
+ {
+ byte packedValue = value0 ? (byte) 1 : (byte) 0;
+
+ if (value1)
+ {
+ packedValue = (byte) (packedValue | (byte)(1 << 1));
+ }
+
+ if (value2)
+ {
+ packedValue = (byte) (packedValue | (byte)(1 << 2));
+ }
+
+ if (value3)
+ {
+ packedValue = (byte) (packedValue | (byte)(1 << 3));
+ }
+
+ if (value4)
+ {
+ packedValue = (byte) (packedValue | (byte)(1 << 4));
+ }
+
+ if (value5)
+ {
+ packedValue = (byte) (packedValue | (byte)(1 << 5));
+ }
+
+ if (value6)
+ {
+ packedValue = (byte) (packedValue | (byte)(1 << 6));
+ }
+
+ if (value7)
+ {
+ packedValue = (byte) (packedValue | (byte)(1 << 7));
+ }
+
+ buffer.put(packedValue);
+ }
+
+
+
+
/**
* This is used for writing longstrs.
*
@@ -282,13 +645,27 @@ public class EncodingUtils
public static boolean[] readBooleans(ByteBuffer buffer)
{
- byte packedValue = buffer.get();
- boolean[] result = new boolean[8];
+ final byte packedValue = buffer.get();
+ if(packedValue == 0)
+ {
+ return ALL_FALSE_ARRAY;
+ }
+ final boolean[] result = new boolean[8];
- for (int i = 0; i < 8; i++)
+ result[0] = ((packedValue & 1) != 0);
+ result[1] = ((packedValue & (1 << 1)) != 0);
+ result[2] = ((packedValue & (1 << 2)) != 0);
+ result[3] = ((packedValue & (1 << 3)) != 0);
+ if((packedValue & 0xF0) == 0)
{
- result[i] = ((packedValue & (1 << i)) != 0);
+ result[0] = ((packedValue & 1) != 0);
}
+ result[4] = ((packedValue & (1 << 4)) != 0);
+ result[5] = ((packedValue & (1 << 5)) != 0);
+ result[6] = ((packedValue & (1 << 6)) != 0);
+ result[7] = ((packedValue & (1 << 7)) != 0);
+
+
return result;
}
@@ -312,6 +689,12 @@ public class EncodingUtils
return content;
}
+ public static AMQShortString readAMQShortString(ByteBuffer buffer)
+ {
+ return AMQShortString.readFromBuffer(buffer);
+
+ }
+
public static String readShortString(ByteBuffer buffer)
{
short length = buffer.getUnsigned();
@@ -363,7 +746,7 @@ public class EncodingUtils
}
}
- public static byte[] readLongstr(ByteBuffer buffer) throws AMQFrameDecodingException
+ public static byte[] readLongstr(ByteBuffer buffer)
{
long length = buffer.getUnsignedInt();
if (length == 0)
@@ -468,7 +851,7 @@ public class EncodingUtils
buffer.put((byte) (aBoolean ? 1 : 0));
}
- public static Boolean readBoolean(ByteBuffer buffer)
+ public static boolean readBoolean(ByteBuffer buffer)
{
byte packedValue = buffer.get();
return (packedValue == 1);
@@ -485,7 +868,7 @@ public class EncodingUtils
buffer.put(aByte);
}
- public static Byte readByte(ByteBuffer buffer)
+ public static byte readByte(ByteBuffer buffer)
{
return buffer.get();
}
@@ -502,7 +885,7 @@ public class EncodingUtils
buffer.putShort(aShort);
}
- public static Short readShort(ByteBuffer buffer)
+ public static short readShort(ByteBuffer buffer)
{
return buffer.getShort();
}
@@ -518,7 +901,7 @@ public class EncodingUtils
buffer.putInt(aInteger);
}
- public static Integer readInteger(ByteBuffer buffer)
+ public static int readInteger(ByteBuffer buffer)
{
return buffer.getInt();
}
@@ -534,7 +917,7 @@ public class EncodingUtils
buffer.putLong(aLong);
}
- public static Long readLong(ByteBuffer buffer)
+ public static long readLong(ByteBuffer buffer)
{
return buffer.getLong();
}
@@ -550,7 +933,7 @@ public class EncodingUtils
buffer.putFloat(aFloat);
}
- public static Float readFloat(ByteBuffer buffer)
+ public static float readFloat(ByteBuffer buffer)
{
return buffer.getFloat();
}
@@ -567,7 +950,7 @@ public class EncodingUtils
buffer.putDouble(aDouble);
}
- public static Double readDouble(ByteBuffer buffer)
+ public static double readDouble(ByteBuffer buffer)
{
return buffer.getDouble();
}
@@ -627,6 +1010,41 @@ public class EncodingUtils
writeByte(buffer, (byte) character);
}
+ public static long readLongAsShortString(ByteBuffer buffer)
+ {
+ short length = buffer.getUnsigned();
+ short pos = 0;
+ if(length == 0)
+ {
+ return 0L;
+ }
+ byte digit = buffer.get();
+ boolean isNegative;
+ long result = 0;
+ if(digit == (byte)'-')
+ {
+ isNegative = true;
+ pos++;
+ digit = buffer.get();
+ }
+ else
+ {
+ isNegative = false;
+ }
+ result = digit - (byte)'0';
+ pos++;
+
+ while(pos < length)
+ {
+ pos++;
+ digit = buffer.get();
+ result = (result << 3) + (result << 1);
+ result += digit - (byte)'0';
+ }
+
+ return result;
+ }
+
public static long readUnsignedInteger(ByteBuffer buffer)
{
long l = 0xFF & buffer.get();
@@ -639,4 +1057,23 @@ public class EncodingUtils
return l;
}
+
+
+ public static void main(String[] args)
+ {
+ ByteBuffer buf = ByteBuffer.allocate(8);
+ buf.setAutoExpand(true);
+
+ long l = (long) Integer.MAX_VALUE;
+ l += 1024L;
+
+ writeUnsignedInteger(buf, l);
+
+ buf.flip();
+
+ long l2 = readUnsignedInteger(buf);
+
+ System.out.println("before: " + l);
+ System.out.println("after: " + l2);
+ }
}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java b/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java
index 3c18683609..61bc9090a1 100644
--- a/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java
+++ b/java/common/src/main/java/org/apache/qpid/framing/FieldTable.java
@@ -31,17 +31,16 @@ public class FieldTable
{
private static final Logger _logger = Logger.getLogger(FieldTable.class);
- private LinkedHashMap<String, AMQTypedValue> _properties;
+ private ByteBuffer _encodedForm;
+ private LinkedHashMap<AMQShortString, AMQTypedValue> _properties;
+ private long _encodedSize;
+ private static final int INITIAL_HASHMAP_CAPACITY = 16;
public FieldTable()
{
super();
- _properties = new LinkedHashMap<String, AMQTypedValue>();
-
}
-
-
/**
* Construct a new field table.
*
@@ -52,14 +51,105 @@ public class FieldTable
public FieldTable(ByteBuffer buffer, long length) throws AMQFrameDecodingException
{
this();
- setFromBuffer(buffer, length);
+ _encodedForm = buffer.slice();
+ _encodedForm.limit((int)length);
+ _encodedSize = length;
+ buffer.skip((int)length);
+ }
+
+
+
+ private AMQTypedValue getProperty(AMQShortString string)
+ {
+ synchronized(this)
+ {
+ if(_properties == null)
+ {
+ if(_encodedForm == null)
+ {
+ return null;
+ }
+ else
+ {
+ populateFromBuffer();
+ }
+ }
+ }
+
+ if(_properties == null)
+ {
+ return null;
+ }
+ else
+ {
+ return _properties.get(string);
+ }
+ }
+
+ private void populateFromBuffer()
+ {
+ try
+ {
+ setFromBuffer(_encodedForm, _encodedSize);
+ }
+ catch (AMQFrameDecodingException e)
+ {
+ _logger.error("Error decoding FieldTable in deferred decoding mode ", e);
+ throw new IllegalArgumentException(e);
+ }
}
+ private AMQTypedValue setProperty(AMQShortString key, AMQTypedValue val)
+ {
+ initMapIfNecessary();
+ _encodedForm = null;
+ if(val == null)
+ {
+ return removeKey(key);
+ }
+ AMQTypedValue oldVal = _properties.put(key,val);
+ if(oldVal != null)
+ {
+ _encodedSize -= oldVal.getEncodingSize();
+ }
+ else
+ {
+ _encodedSize += EncodingUtils.encodedShortStringLength(key) + 1;
+ }
+ _encodedSize += val.getEncodingSize();
+
+ return oldVal;
+ }
+
+ private void initMapIfNecessary()
+ {
+ synchronized(this)
+ {
+ if(_properties == null)
+ {
+ if(_encodedForm == null)
+ {
+ _properties = new LinkedHashMap<AMQShortString,AMQTypedValue>();
+ }
+ else
+ {
+ populateFromBuffer();
+ }
+ }
+
+ }
+ }
+
public Boolean getBoolean(String string)
{
- AMQTypedValue value = _properties.get(string);
+ return getBoolean(new AMQShortString(string));
+ }
+
+ public Boolean getBoolean(AMQShortString string)
+ {
+ AMQTypedValue value = getProperty(string);
if (value != null && (value.getType() == AMQType.BOOLEAN))
{
return (Boolean) value.getValue();
@@ -70,9 +160,15 @@ public class FieldTable
}
}
+
public Byte getByte(String string)
{
- AMQTypedValue value = _properties.get(string);
+ return getByte(new AMQShortString(string));
+ }
+
+ public Byte getByte(AMQShortString string)
+ {
+ AMQTypedValue value = getProperty(string);
if (value != null && (value.getType() == AMQType.BYTE))
{
return (Byte) value.getValue();
@@ -85,7 +181,12 @@ public class FieldTable
public Short getShort(String string)
{
- AMQTypedValue value = _properties.get(string);
+ return getShort(new AMQShortString(string));
+ }
+
+ public Short getShort(AMQShortString string)
+ {
+ AMQTypedValue value = getProperty(string);
if (value != null && (value.getType() == AMQType.SHORT))
{
return (Short) value.getValue();
@@ -98,7 +199,12 @@ public class FieldTable
public Integer getInteger(String string)
{
- AMQTypedValue value = _properties.get(string);
+ return getInteger(new AMQShortString(string));
+ }
+
+ public Integer getInteger(AMQShortString string)
+ {
+ AMQTypedValue value = getProperty(string);
if (value != null && (value.getType() == AMQType.INT))
{
return (Integer) value.getValue();
@@ -111,7 +217,12 @@ public class FieldTable
public Long getLong(String string)
{
- AMQTypedValue value = _properties.get(string);
+ return getLong(new AMQShortString(string));
+ }
+
+ public Long getLong(AMQShortString string)
+ {
+ AMQTypedValue value = getProperty(string);
if (value != null && (value.getType() == AMQType.LONG))
{
return (Long) value.getValue();
@@ -124,7 +235,12 @@ public class FieldTable
public Float getFloat(String string)
{
- AMQTypedValue value = _properties.get(string);
+ return getFloat(new AMQShortString(string));
+ }
+
+ public Float getFloat(AMQShortString string)
+ {
+ AMQTypedValue value = getProperty(string);
if (value != null && (value.getType() == AMQType.FLOAT))
{
return (Float) value.getValue();
@@ -137,7 +253,12 @@ public class FieldTable
public Double getDouble(String string)
{
- AMQTypedValue value = _properties.get(string);
+ return getDouble(new AMQShortString(string));
+ }
+
+ public Double getDouble(AMQShortString string)
+ {
+ AMQTypedValue value = getProperty(string);
if (value != null && (value.getType() == AMQType.DOUBLE))
{
return (Double) value.getValue();
@@ -150,7 +271,12 @@ public class FieldTable
public String getString(String string)
{
- AMQTypedValue value = _properties.get(string);
+ return getString(new AMQShortString(string));
+ }
+
+ public String getString(AMQShortString string)
+ {
+ AMQTypedValue value = getProperty(string);
if ((value != null) && ((value.getType() == AMQType.WIDE_STRING) ||
(value.getType() == AMQType.ASCII_STRING)))
{
@@ -170,7 +296,12 @@ public class FieldTable
public Character getCharacter(String string)
{
- AMQTypedValue value = _properties.get(string);
+ return getCharacter(new AMQShortString(string));
+ }
+
+ public Character getCharacter(AMQShortString string)
+ {
+ AMQTypedValue value = getProperty(string);
if (value != null && (value.getType() == AMQType.ASCII_CHARACTER))
{
return (Character) value.getValue();
@@ -183,7 +314,12 @@ public class FieldTable
public byte[] getBytes(String string)
{
- AMQTypedValue value = _properties.get(string);
+ return getBytes(new AMQShortString(string));
+ }
+
+ public byte[] getBytes(AMQShortString string)
+ {
+ AMQTypedValue value = getProperty(string);
if (value != null && (value.getType() == AMQType.BINARY))
{
return (byte[]) value.getValue();
@@ -196,7 +332,12 @@ public class FieldTable
public Object getObject(String string)
{
- AMQTypedValue value = _properties.get(string);
+ return getObject(new AMQShortString(string));
+ }
+
+ public Object getObject(AMQShortString string)
+ {
+ AMQTypedValue value = getProperty(string);
if(value != null)
{
return value.getValue();
@@ -209,92 +350,163 @@ public class FieldTable
}
// ************ Setters
-
public Object setBoolean(String string, boolean b)
{
+ return setBoolean(new AMQShortString(string), b);
+ }
+
+ public Object setBoolean(AMQShortString string, boolean b)
+ {
checkPropertyName(string);
- return _properties.put(string, AMQType.BOOLEAN.asTypedValue(b));
+ return setProperty(string, AMQType.BOOLEAN.asTypedValue(b));
}
public Object setByte(String string, byte b)
{
+ return setByte(new AMQShortString(string), b);
+ }
+
+ public Object setByte(AMQShortString string, byte b)
+ {
checkPropertyName(string);
- return _properties.put(string, AMQType.BYTE.asTypedValue(b));
+ return setProperty(string, AMQType.BYTE.asTypedValue(b));
}
public Object setShort(String string, short i)
{
+ return setShort(new AMQShortString(string), i);
+ }
+
+ public Object setShort(AMQShortString string, short i)
+ {
checkPropertyName(string);
- return _properties.put(string, AMQType.SHORT.asTypedValue(i));
+ return setProperty(string, AMQType.SHORT.asTypedValue(i));
}
+
public Object setInteger(String string, int i)
{
+ return setInteger(new AMQShortString(string), i);
+ }
+
+ public Object setInteger(AMQShortString string, int i)
+ {
checkPropertyName(string);
- return _properties.put(string, AMQType.INT.asTypedValue(i));
+ return setProperty(string, AMQType.INT.asTypedValue(i));
}
+
public Object setLong(String string, long l)
{
+ return setLong(new AMQShortString(string), l);
+ }
+
+ public Object setLong(AMQShortString string, long l)
+ {
checkPropertyName(string);
- return _properties.put(string, AMQType.LONG.asTypedValue(l));
+ return setProperty(string, AMQType.LONG.asTypedValue(l));
}
- public Object setFloat(String string, float v)
+
+ public Object setFloat(String string, float f)
+ {
+ return setFloat(new AMQShortString(string), f);
+ }
+
+ public Object setFloat(AMQShortString string, float v)
{
checkPropertyName(string);
- return _properties.put(string, AMQType.FLOAT.asTypedValue(v));
+ return setProperty(string, AMQType.FLOAT.asTypedValue(v));
}
- public Object setDouble(String string, double v)
+ public Object setDouble(String string, double d)
+ {
+ return setDouble(new AMQShortString(string), d);
+ }
+
+
+ public Object setDouble(AMQShortString string, double v)
{
checkPropertyName(string);
- return _properties.put(string, AMQType.DOUBLE.asTypedValue(v));
+ return setProperty(string, AMQType.DOUBLE.asTypedValue(v));
+ }
+
+
+ public Object setString(String string, String s)
+ {
+ return setString(new AMQShortString(string), s);
}
- public Object setString(String string, String value)
+ public Object setAsciiString(AMQShortString string, String value)
{
checkPropertyName(string);
if (value == null)
{
- return _properties.put(string, AMQType.VOID.asTypedValue(null));
+ return setProperty(string, AMQType.VOID.asTypedValue(null));
}
else
{
- //FIXME: determine string encoding and set either WIDE or ASCII string
-// if ()
- {
- return _properties.put(string, AMQType.WIDE_STRING.asTypedValue(value));
- }
-// else
-// {
-// return _properties.put(string, AMQType.ASCII_STRING.asTypedValue(value));
-// }
+ return setProperty(string, AMQType.ASCII_STRING.asTypedValue(value));
}
}
+ public Object setString(AMQShortString string, String value)
+ {
+ checkPropertyName(string);
+ if (value == null)
+ {
+ return setProperty(string, AMQType.VOID.asTypedValue(null));
+ }
+ else
+ {
+ return setProperty(string, AMQType.LONG_STRING.asTypedValue(value));
+ }
+ }
+
+
public Object setChar(String string, char c)
{
+ return setChar(new AMQShortString(string), c);
+ }
+
+
+ public Object setChar(AMQShortString string, char c)
+ {
checkPropertyName(string);
- return _properties.put(string, AMQType.ASCII_CHARACTER.asTypedValue(c));
+ return setProperty(string, AMQType.ASCII_CHARACTER.asTypedValue(c));
}
- public Object setBytes(String string, byte[] bytes)
+
+ public Object setBytes(String string, byte[] b)
+ {
+ return setBytes(new AMQShortString(string), b);
+ }
+
+ public Object setBytes(AMQShortString string, byte[] bytes)
{
checkPropertyName(string);
- return _properties.put(string, AMQType.BINARY.asTypedValue(bytes));
+ return setProperty(string, AMQType.BINARY.asTypedValue(bytes));
}
public Object setBytes(String string, byte[] bytes, int start, int length)
{
+ return setBytes(new AMQShortString(string), bytes,start,length);
+ }
+
+ public Object setBytes(AMQShortString string, byte[] bytes, int start, int length)
+ {
checkPropertyName(string);
byte[] newBytes = new byte[length];
System.arraycopy(bytes,start,newBytes,0,length);
return setBytes(string, bytes);
}
+ public Object setObject(String string, Object o)
+ {
+ return setObject(new AMQShortString(string), o);
+ }
- public Object setObject(String string, Object object)
+ public Object setObject(AMQShortString string, Object object)
{
if (object instanceof Boolean)
{
@@ -343,7 +555,7 @@ public class FieldTable
public boolean isNullStringValue(String name)
{
- AMQTypedValue value = _properties.get(name);
+ AMQTypedValue value = getProperty(new AMQShortString(name));
return (value != null) && (value.getType() == AMQType.VOID);
}
@@ -351,7 +563,12 @@ public class FieldTable
public Enumeration getPropertyNames()
{
- return Collections.enumeration(_properties.keySet());
+ return Collections.enumeration(keys());
+ }
+
+ public boolean propertyExists(AMQShortString propertyName)
+ {
+ return itemExists(propertyName);
}
public boolean propertyExists(String propertyName)
@@ -359,25 +576,34 @@ public class FieldTable
return itemExists(propertyName);
}
- public boolean itemExists(String string)
+ public boolean itemExists(AMQShortString string)
{
+ initMapIfNecessary();
return _properties.containsKey(string);
}
+ public boolean itemExists(String string)
+ {
+ return itemExists(new AMQShortString(string));
+ }
+
public String toString()
{
+ initMapIfNecessary();
+// if (_encodedForm != null)
+// _encodedForm.rewind();
return _properties.toString();
}
- private void checkPropertyName(String propertyName)
+ private void checkPropertyName(AMQShortString propertyName)
{
if (propertyName == null)
{
throw new IllegalArgumentException("Property name must not be null");
}
- else if ("".equals(propertyName))
+ else if (propertyName.length()==0)
{
throw new IllegalArgumentException("Property name must not be the empty string");
}
@@ -386,7 +612,7 @@ public class FieldTable
}
- protected static void checkIdentiferFormat(String propertyName)
+ protected static void checkIdentiferFormat(AMQShortString propertyName)
{
// AMQP Spec: 4.2.5.5 Field Tables
// Guidelines for implementers:
@@ -448,20 +674,31 @@ public class FieldTable
public long getEncodedSize()
{
+ return _encodedSize;
+ }
+
+ private void recalculateEncodedSize()
+ {
+
int encodedSize = 0;
- for(Map.Entry<String,AMQTypedValue> e : _properties.entrySet())
+ if(_properties != null)
{
- encodedSize += EncodingUtils.encodedShortStringLength(e.getKey());
- encodedSize++; // the byte for the encoding Type
- encodedSize += e.getValue().getEncodingSize();
+ for(Map.Entry<AMQShortString,AMQTypedValue> e : _properties.entrySet())
+ {
+ encodedSize += EncodingUtils.encodedShortStringLength(e.getKey());
+ encodedSize++; // the byte for the encoding Type
+ encodedSize += e.getValue().getEncodingSize();
+ }
}
- return encodedSize;
+ _encodedSize = encodedSize;
}
public void addAll(FieldTable fieldTable)
{
+ initMapIfNecessary();
_properties.putAll(fieldTable._properties);
+ recalculateEncodedSize();
}
@@ -473,135 +710,213 @@ public class FieldTable
public Object processOverElements(FieldTableElementProcessor processor)
{
- for(Map.Entry<String,AMQTypedValue> e : _properties.entrySet())
+ initMapIfNecessary();
+ if(_properties != null)
{
- boolean result = processor.processElement(e.getKey(), e.getValue());
- if(!result)
+ for(Map.Entry<AMQShortString,AMQTypedValue> e : _properties.entrySet())
{
- break;
+ boolean result = processor.processElement(e.getKey().toString(), e.getValue());
+ if(!result)
+ {
+ break;
+ }
}
}
return processor.getResult();
+
+
}
public int size()
{
+ initMapIfNecessary();
return _properties.size();
+
}
public boolean isEmpty()
{
- return _properties.isEmpty();
+ return size() ==0;
}
- public boolean containsKey(String key)
+ public boolean containsKey(AMQShortString key)
{
+ initMapIfNecessary();
return _properties.containsKey(key);
}
+ public boolean containsKey(String key)
+ {
+ return containsKey(new AMQShortString(key));
+ }
+
public Set<String> keys()
{
- return _properties.keySet();
+ initMapIfNecessary();
+ Set<String> keys = new LinkedHashSet<String>();
+ for(AMQShortString key : _properties.keySet())
+ {
+ keys.add(key.toString());
+ }
+ return keys;
}
- public Object get(Object key)
+ public Object get(AMQShortString key)
{
- return getObject((String)key);
+ return getObject(key);
}
- public Object put(Object key, Object value)
+
+ public Object put(AMQShortString key, Object value)
{
- return setObject(key.toString(), value);
+ return setObject(key, value);
}
-
+
public Object remove(String key)
{
+
+ return remove(new AMQShortString(key));
+
+ }
+
+ public Object remove(AMQShortString key)
+ {
+ AMQTypedValue val = removeKey(key);
+ return val == null ? null : val.getValue();
+
+ }
+
+
+ public AMQTypedValue removeKey(AMQShortString key)
+ {
+ initMapIfNecessary();
+ _encodedForm = null;
AMQTypedValue value = _properties.remove(key);
- return value == null ? null : value.getValue();
+ if(value == null)
+ {
+ return null;
+ }
+ else
+ {
+ _encodedSize -= EncodingUtils.encodedShortStringLength(key);
+ _encodedSize--;
+ _encodedSize -= value.getEncodingSize();
+ return value;
+ }
+
}
public void clear()
{
+ initMapIfNecessary();
+ _encodedForm = null;
_properties.clear();
+ _encodedSize = 0;
}
- public Set keySet()
+ public Set<AMQShortString> keySet()
{
+ initMapIfNecessary();
return _properties.keySet();
}
private void putDataInBuffer(ByteBuffer buffer)
{
- final Iterator<Map.Entry<String,AMQTypedValue>> it = _properties.entrySet().iterator();
+ if(_encodedForm != null)
+ {
+ if (_encodedForm.remaining() == 0)
+ {
+ _encodedForm.rewind();
+ }
+ buffer.put(_encodedForm);
+ }
+ else if(_properties != null)
+ {
+ final Iterator<Map.Entry<AMQShortString,AMQTypedValue>> it = _properties.entrySet().iterator();
- //If there are values then write out the encoded Size... could check _encodedSize != 0
- // write out the total length, which we have kept up to date as data is added
+ //If there are values then write out the encoded Size... could check _encodedSize != 0
+ // write out the total length, which we have kept up to date as data is added
- while (it.hasNext())
- {
- final Map.Entry<String,AMQTypedValue> me = it.next();
- try
+ while (it.hasNext())
{
- if (_logger.isTraceEnabled())
+ final Map.Entry<AMQShortString,AMQTypedValue> me = it.next();
+ try
{
- _logger.trace("Writing Property:" + me.getKey() +
- " Type:" + me.getValue().getType() +
- " Value:" + me.getValue().getValue());
- _logger.trace("Buffer Position:" + buffer.position() +
- " Remaining:" + buffer.remaining());
- }
+ if (_logger.isTraceEnabled())
+ {
+ _logger.trace("Writing Property:" + me.getKey() +
+ " Type:" + me.getValue().getType() +
+ " Value:" + me.getValue().getValue());
+ _logger.trace("Buffer Position:" + buffer.position() +
+ " Remaining:" + buffer.remaining());
+ }
- //Write the actual parameter name
- EncodingUtils.writeShortStringBytes(buffer, me.getKey());
- me.getValue().writeToBuffer(buffer);
- }
- catch (Exception e)
- {
- if (_logger.isTraceEnabled())
+ //Write the actual parameter name
+ EncodingUtils.writeShortStringBytes(buffer, me.getKey());
+ me.getValue().writeToBuffer(buffer);
+ }
+ catch (Exception e)
{
- _logger.trace("Exception thrown:" + e);
- _logger.trace("Writing Property:" + me.getKey() +
- " Type:" + me.getValue().getType() +
- " Value:" + me.getValue().getValue());
- _logger.trace("Buffer Position:" + buffer.position() +
- " Remaining:" + buffer.remaining());
+ if (_logger.isTraceEnabled())
+ {
+ _logger.trace("Exception thrown:" + e);
+ _logger.trace("Writing Property:" + me.getKey() +
+ " Type:" + me.getValue().getType() +
+ " Value:" + me.getValue().getValue());
+ _logger.trace("Buffer Position:" + buffer.position() +
+ " Remaining:" + buffer.remaining());
+ }
+ throw new RuntimeException(e);
}
- throw new RuntimeException(e);
}
}
}
- public void setFromBuffer(ByteBuffer buffer, long length) throws AMQFrameDecodingException
+ private void setFromBuffer(ByteBuffer buffer, long length) throws AMQFrameDecodingException
{
- final boolean trace = _logger.isTraceEnabled();
- int sizeRead = 0;
- while (sizeRead < length)
+ final boolean trace = _logger.isTraceEnabled();
+ if(length > 0)
{
- int sizeRemaining = buffer.remaining();
- final String key = EncodingUtils.readShortString(buffer);
- AMQTypedValue value = AMQTypedValue.readFromBuffer(buffer);
- sizeRead += (sizeRemaining - buffer.remaining());
- if (trace)
+ final int expectedRemaining = buffer.remaining()-(int)length;
+
+ _properties = new LinkedHashMap<AMQShortString,AMQTypedValue>(INITIAL_HASHMAP_CAPACITY);
+
+ do
{
- _logger.trace("FieldTable::PropFieldTable(buffer," + length + "): Read type '" + value.getType() + "', key '" + key + "', value '" + value.getValue() + "' (now read " + sizeRead + " of " + length + " encoded bytes)...");
+
+ final AMQShortString key = EncodingUtils.readAMQShortString(buffer);
+ AMQTypedValue value = AMQTypedValue.readFromBuffer(buffer);
+
+ if (trace)
+ {
+ _logger.trace("FieldTable::PropFieldTable(buffer," + length + "): Read type '" + value.getType() + "', key '" + key + "', value '" + value.getValue() + "'");
+ }
+
+
+
+ _properties.put(key,value);
+
+
+
}
+ while (buffer.remaining() > expectedRemaining);
- _properties.put(key,value);
}
+ _encodedSize = length;
if (trace)
{
diff --git a/java/common/src/main/java/org/apache/qpid/framing/HeartbeatBody.java b/java/common/src/main/java/org/apache/qpid/framing/HeartbeatBody.java
index 7a160ef471..7246c4a1cf 100644
--- a/java/common/src/main/java/org/apache/qpid/framing/HeartbeatBody.java
+++ b/java/common/src/main/java/org/apache/qpid/framing/HeartbeatBody.java
@@ -27,7 +27,21 @@ public class HeartbeatBody extends AMQBody
public static final byte TYPE = 8;
public static AMQFrame FRAME = new HeartbeatBody().toFrame();
- protected byte getFrameType()
+ public HeartbeatBody()
+ {
+
+ }
+
+ public HeartbeatBody(ByteBuffer buffer, long size)
+ {
+ if(size > 0)
+ {
+ //allow other implementations to have a payload, but ignore it:
+ buffer.skip((int) size);
+ }
+ }
+
+ public byte getFrameType()
{
return TYPE;
}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/HeartbeatBodyFactory.java b/java/common/src/main/java/org/apache/qpid/framing/HeartbeatBodyFactory.java
index 97bd3d9253..c7ada708dc 100644
--- a/java/common/src/main/java/org/apache/qpid/framing/HeartbeatBodyFactory.java
+++ b/java/common/src/main/java/org/apache/qpid/framing/HeartbeatBodyFactory.java
@@ -24,7 +24,7 @@ import org.apache.mina.common.ByteBuffer;
public class HeartbeatBodyFactory implements BodyFactory
{
- public AMQBody createBody(ByteBuffer in) throws AMQFrameDecodingException
+ public AMQBody createBody(ByteBuffer in, long bodySize) throws AMQFrameDecodingException
{
return new HeartbeatBody();
}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/ProtocolInitiation.java b/java/common/src/main/java/org/apache/qpid/framing/ProtocolInitiation.java
index f2d1a70cdc..697a0f4249 100644
--- a/java/common/src/main/java/org/apache/qpid/framing/ProtocolInitiation.java
+++ b/java/common/src/main/java/org/apache/qpid/framing/ProtocolInitiation.java
@@ -164,4 +164,14 @@ public class ProtocolInitiation extends AMQDataBlock implements EncodableAMQData
protocolMajor + "." + protocolMinor + " not found in protocol version list.");
}
}
+
+ public String toString()
+ {
+ StringBuffer buffer = new StringBuffer(new String(header));
+ buffer.append(Integer.toHexString(protocolClass));
+ buffer.append(Integer.toHexString(protocolInstance));
+ buffer.append(Integer.toHexString(protocolMajor));
+ buffer.append(Integer.toHexString(protocolMinor));
+ return buffer.toString();
+ }
}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/RequestManager.java b/java/common/src/main/java/org/apache/qpid/framing/RequestManager.java
index 836c4ad985..eab7ad0132 100644
--- a/java/common/src/main/java/org/apache/qpid/framing/RequestManager.java
+++ b/java/common/src/main/java/org/apache/qpid/framing/RequestManager.java
@@ -40,7 +40,7 @@ public class RequestManager
* to be known.
*/
private boolean serverFlag;
- private int connectionId;
+ private long connectionId;
/**
* Request and response frames must have a requestID and responseID which
@@ -56,7 +56,7 @@ public class RequestManager
private ConcurrentHashMap<Long, AMQMethodListener> requestSentMap;
- public RequestManager(int connectionId, int channel, AMQProtocolWriter protocolWriter, boolean serverFlag)
+ public RequestManager(long connectionId, int channel, AMQProtocolWriter protocolWriter, boolean serverFlag)
{
this.channel = channel;
this.protocolWriter = protocolWriter;
diff --git a/java/common/src/main/java/org/apache/qpid/framing/ResponseManager.java b/java/common/src/main/java/org/apache/qpid/framing/ResponseManager.java
index 3148603d65..9896bde5f8 100644
--- a/java/common/src/main/java/org/apache/qpid/framing/ResponseManager.java
+++ b/java/common/src/main/java/org/apache/qpid/framing/ResponseManager.java
@@ -43,7 +43,7 @@ public class ResponseManager
* to be known.
*/
private boolean serverFlag;
- private int connectionId;
+ private long connectionId;
private int maxAccumulatedResponses = 20; // Default
// private Class currentResponseMethodBodyClass;
@@ -80,11 +80,18 @@ public class ResponseManager
{
return (int)(requestId - o.requestId);
}
+
+ public String toString()
+ {
+ return requestId + ":" + (responseMethodBody == null ?
+ "null" :
+ "C" + responseMethodBody.getClazz() + " M" + responseMethodBody.getMethod());
+ }
}
private ConcurrentHashMap<Long, ResponseStatus> responseMap;
- public ResponseManager(int connectionId, int channel, AMQMethodListener methodListener,
+ public ResponseManager(long connectionId, int channel, AMQMethodListener methodListener,
AMQProtocolWriter protocolWriter, boolean serverFlag)
{
this.channel = channel;
diff --git a/java/common/src/main/java/org/apache/qpid/framing/SmallCompositeAMQDataBlock.java b/java/common/src/main/java/org/apache/qpid/framing/SmallCompositeAMQDataBlock.java
new file mode 100644
index 0000000000..0dd1bdc102
--- /dev/null
+++ b/java/common/src/main/java/org/apache/qpid/framing/SmallCompositeAMQDataBlock.java
@@ -0,0 +1,97 @@
+/*
+ *
+ * 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.framing;
+
+import org.apache.mina.common.ByteBuffer;
+
+public class SmallCompositeAMQDataBlock extends AMQDataBlock implements EncodableAMQDataBlock
+{
+ private ByteBuffer _encodedBlock;
+
+ private AMQDataBlock _block;
+
+ public SmallCompositeAMQDataBlock(AMQDataBlock block)
+ {
+ _block = block;
+ }
+
+ /**
+ * The encoded block will be logically first before the AMQDataBlocks which are encoded
+ * into the buffer afterwards.
+ * @param encodedBlock already-encoded data
+ * @param block a block to be encoded.
+ */
+ public SmallCompositeAMQDataBlock(ByteBuffer encodedBlock, AMQDataBlock block)
+ {
+ this(block);
+ _encodedBlock = encodedBlock;
+ }
+
+ public AMQDataBlock getBlock()
+ {
+ return _block;
+ }
+
+ public ByteBuffer getEncodedBlock()
+ {
+ return _encodedBlock;
+ }
+
+ public long getSize()
+ {
+ long frameSize = _block.getSize();
+
+ if (_encodedBlock != null)
+ {
+ _encodedBlock.rewind();
+ frameSize += _encodedBlock.remaining();
+ }
+ return frameSize;
+ }
+
+ public void writePayload(ByteBuffer buffer)
+ {
+ if (_encodedBlock != null)
+ {
+ buffer.put(_encodedBlock);
+ }
+ _block.writePayload(buffer);
+
+ }
+
+ public String toString()
+ {
+ if (_block == null)
+ {
+ return "No blocks contained in composite frame";
+ }
+ else
+ {
+ StringBuilder buf = new StringBuilder(this.getClass().getName());
+ buf.append("{encodedBlock=").append(_encodedBlock);
+
+ buf.append(" _block=[").append(_block.toString()).append("]");
+
+ buf.append("}");
+ return buf.toString();
+ }
+ }
+}
diff --git a/java/common/src/main/java/org/apache/qpid/framing/VersionSpecificRegistry.java b/java/common/src/main/java/org/apache/qpid/framing/VersionSpecificRegistry.java
new file mode 100644
index 0000000000..9bc8232d61
--- /dev/null
+++ b/java/common/src/main/java/org/apache/qpid/framing/VersionSpecificRegistry.java
@@ -0,0 +1,141 @@
+/*
+ *
+ * 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.framing;
+
+import org.apache.mina.common.ByteBuffer;
+import org.apache.log4j.Logger;
+
+public class VersionSpecificRegistry
+{
+ private static final Logger _log = Logger.getLogger(VersionSpecificRegistry.class);
+
+
+ private final byte _protocolMajorVersion;
+ private final byte _protocolMinorVersion;
+
+ private static final int DEFAULT_MAX_CLASS_ID = 200;
+ private static final int DEFAULT_MAX_METHOD_ID = 50;
+
+ private AMQMethodBodyInstanceFactory[][] _registry = new AMQMethodBodyInstanceFactory[DEFAULT_MAX_CLASS_ID][];
+
+ public VersionSpecificRegistry(byte major, byte minor)
+ {
+ _protocolMajorVersion = major;
+ _protocolMinorVersion = minor;
+ }
+
+ public byte getProtocolMajorVersion()
+ {
+ return _protocolMajorVersion;
+ }
+
+ public byte getProtocolMinorVersion()
+ {
+ return _protocolMinorVersion;
+ }
+
+ public AMQMethodBodyInstanceFactory getMethodBody(final short classID, final short methodID)
+ {
+ try
+ {
+ return _registry[classID][methodID];
+ }
+ catch (IndexOutOfBoundsException e)
+ {
+ return null;
+ }
+ catch (NullPointerException e)
+ {
+ return null;
+ }
+ }
+
+ public void registerMethod(final short classID, final short methodID, final AMQMethodBodyInstanceFactory instanceFactory)
+ {
+ if(_registry.length <= classID)
+ {
+ AMQMethodBodyInstanceFactory[][] oldRegistry = _registry;
+ _registry = new AMQMethodBodyInstanceFactory[classID+1][];
+ System.arraycopy(oldRegistry, 0, _registry, 0, oldRegistry.length);
+ }
+
+ if(_registry[classID] == null)
+ {
+ _registry[classID] = new AMQMethodBodyInstanceFactory[methodID > DEFAULT_MAX_METHOD_ID ? methodID + 1 : DEFAULT_MAX_METHOD_ID + 1];
+ }
+ else if(_registry[classID].length <= methodID)
+ {
+ AMQMethodBodyInstanceFactory[] oldMethods = _registry[classID];
+ _registry[classID] = new AMQMethodBodyInstanceFactory[methodID+1];
+ System.arraycopy(oldMethods,0,_registry[classID],0,oldMethods.length);
+ }
+
+ _registry[classID][methodID] = instanceFactory;
+
+ }
+
+
+ public AMQMethodBody get(short classID, short methodID, ByteBuffer in, long size)
+ throws AMQFrameDecodingException
+ {
+ AMQMethodBodyInstanceFactory bodyFactory;
+ try
+ {
+ bodyFactory = _registry[classID][methodID];
+ }
+ catch(NullPointerException e)
+ {
+ throw new AMQFrameDecodingException(_log,
+ "Class " + classID + " unknown in AMQP version " + _protocolMajorVersion + "-" + _protocolMinorVersion
+ + " (while trying to decode class " + classID + " method " + methodID + ".");
+ }
+ catch(IndexOutOfBoundsException e)
+ {
+ if(classID >= _registry.length)
+ {
+ throw new AMQFrameDecodingException(_log,
+ "Class " + classID + " unknown in AMQP version " + _protocolMajorVersion + "-" + _protocolMinorVersion
+ + " (while trying to decode class " + classID + " method " + methodID + ".");
+
+ }
+ else
+ {
+ throw new AMQFrameDecodingException(_log,
+ "Method " + methodID + " unknown in AMQP version " + _protocolMajorVersion + "-" + _protocolMinorVersion
+ + " (while trying to decode class " + classID + " method " + methodID + ".");
+
+ }
+ }
+
+
+ if (bodyFactory == null)
+ {
+ throw new AMQFrameDecodingException(_log,
+ "Method " + methodID + " unknown in AMQP version " + _protocolMajorVersion + "-" + _protocolMinorVersion
+ + " (while trying to decode class " + classID + " method " + methodID + ".");
+ }
+
+
+ return bodyFactory.newInstance(_protocolMajorVersion, _protocolMinorVersion, classID, methodID, in, size);
+
+
+ }
+}
diff --git a/java/common/src/main/java/org/apache/qpid/pool/Event.java b/java/common/src/main/java/org/apache/qpid/pool/Event.java
index 7364b9293a..43ff8f6a19 100644
--- a/java/common/src/main/java/org/apache/qpid/pool/Event.java
+++ b/java/common/src/main/java/org/apache/qpid/pool/Event.java
@@ -25,90 +25,66 @@ import org.apache.mina.common.IoFilter;
import org.apache.mina.common.IoSession;
import org.apache.mina.common.IdleStatus;
-/**
- * Represents an operation on IoFilter.
- */
-enum EventType
-{
- OPENED, CLOSED, READ, WRITE, WRITTEN, RECEIVED, SENT, IDLE, EXCEPTION
-}
-class Event
+abstract public class Event
{
- private static final Logger _log = Logger.getLogger(Event.class);
-
- private final EventType type;
- private final IoFilter.NextFilter nextFilter;
- private final Object data;
-
- public Event(IoFilter.NextFilter nextFilter, EventType type, Object data)
- {
- this.type = type;
- this.nextFilter = nextFilter;
- this.data = data;
- if (type == EventType.EXCEPTION)
- {
- _log.error("Exception event constructed: " + data, (Throwable) data);
- }
- }
- public Object getData()
+ public Event()
{
- return data;
}
- public IoFilter.NextFilter getNextFilter()
- {
- return nextFilter;
- }
+ abstract public void process(IoSession session);
- public EventType getType()
+ public static final class ReceivedEvent extends Event
{
- return type;
- }
+ private final Object _data;
- void process(IoSession session)
- {
- if (_log.isDebugEnabled())
- {
- _log.debug("Processing " + this);
- }
- if (type == EventType.RECEIVED)
- {
- nextFilter.messageReceived(session, data);
- //ByteBufferUtil.releaseIfPossible( data );
- }
- else if (type == EventType.SENT)
+ private final IoFilter.NextFilter _nextFilter;
+
+ public ReceivedEvent(final IoFilter.NextFilter nextFilter, final Object data)
{
- nextFilter.messageSent(session, data);
- //ByteBufferUtil.releaseIfPossible( data );
+ super();
+ _nextFilter = nextFilter;
+ _data = data;
}
- else if (type == EventType.EXCEPTION)
+
+ public void process(IoSession session)
{
- nextFilter.exceptionCaught(session, (Throwable) data);
+ _nextFilter.messageReceived(session, _data);
}
- else if (type == EventType.IDLE)
+
+ public IoFilter.NextFilter getNextFilter()
{
- nextFilter.sessionIdle(session, (IdleStatus) data);
+ return _nextFilter;
}
- else if (type == EventType.OPENED)
+ }
+
+
+ public static final class WriteEvent extends Event
+ {
+ private final IoFilter.WriteRequest _data;
+ private final IoFilter.NextFilter _nextFilter;
+
+ public WriteEvent(final IoFilter.NextFilter nextFilter, final IoFilter.WriteRequest data)
{
- nextFilter.sessionOpened(session);
+ super();
+ _nextFilter = nextFilter;
+ _data = data;
}
- else if (type == EventType.WRITE)
+
+
+ public void process(IoSession session)
{
- nextFilter.filterWrite(session, (IoFilter.WriteRequest) data);
+ _nextFilter.filterWrite(session, _data);
}
- else if (type == EventType.CLOSED)
+
+ public IoFilter.NextFilter getNextFilter()
{
- nextFilter.sessionClosed(session);
+ return _nextFilter;
}
}
- public String toString()
- {
- return "Event: type " + type + ", data: " + data;
- }
+
}
diff --git a/java/common/src/main/java/org/apache/qpid/pool/Job.java b/java/common/src/main/java/org/apache/qpid/pool/Job.java
index b9673cd48f..9b3bcfa008 100644
--- a/java/common/src/main/java/org/apache/qpid/pool/Job.java
+++ b/java/common/src/main/java/org/apache/qpid/pool/Job.java
@@ -30,13 +30,13 @@ import java.util.concurrent.atomic.AtomicInteger;
* Holds events for a session that will be processed asynchronously by
* the thread pool in PoolingFilter.
*/
-class Job implements Runnable
+public class Job implements Runnable
{
private final int _maxEvents;
private final IoSession _session;
private final java.util.Queue<Event> _eventQueue = new ConcurrentLinkedQueue<Event>();
private final AtomicBoolean _active = new AtomicBoolean();
- private final AtomicInteger _refCount = new AtomicInteger();
+ //private final AtomicInteger _refCount = new AtomicInteger();
private final JobCompletionHandler _completionHandler;
Job(IoSession session, JobCompletionHandler completionHandler, int maxEvents)
@@ -45,21 +45,21 @@ class Job implements Runnable
_completionHandler = completionHandler;
_maxEvents = maxEvents;
}
-
- void acquire()
- {
- _refCount.incrementAndGet();
- }
-
- void release()
- {
- _refCount.decrementAndGet();
- }
-
- boolean isReferenced()
- {
- return _refCount.get() > 0;
- }
+//
+// void acquire()
+// {
+// _refCount.incrementAndGet();
+// }
+//
+// void release()
+// {
+// _refCount.decrementAndGet();
+// }
+//
+// boolean isReferenced()
+// {
+// return _refCount.get() > 0;
+// }
void add(Event evt)
{
diff --git a/java/common/src/main/java/org/apache/qpid/pool/PoolingFilter.java b/java/common/src/main/java/org/apache/qpid/pool/PoolingFilter.java
index 38cfa68c78..9d04827246 100644
--- a/java/common/src/main/java/org/apache/qpid/pool/PoolingFilter.java
+++ b/java/common/src/main/java/org/apache/qpid/pool/PoolingFilter.java
@@ -25,57 +25,60 @@ import org.apache.mina.common.IdleStatus;
import org.apache.mina.common.IoFilterAdapter;
import org.apache.mina.common.IoSession;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Set;
+import java.util.EnumSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class PoolingFilter extends IoFilterAdapter implements Job.JobCompletionHandler
{
private static final Logger _logger = Logger.getLogger(PoolingFilter.class);
- public static final Set<EventType> READ_EVENTS = new HashSet<EventType>(Arrays.asList(EventType.RECEIVED));
- public static final Set<EventType> WRITE_EVENTS = new HashSet<EventType>(Arrays.asList(EventType.WRITE));
private final ConcurrentMap<IoSession, Job> _jobs = new ConcurrentHashMap<IoSession, Job>();
private final ReferenceCountingExecutorService _poolReference;
- private final Set<EventType> _asyncTypes;
private final String _name;
private final int _maxEvents = Integer.getInteger("amqj.server.read_write_pool.max_events", 10);
- public PoolingFilter(ReferenceCountingExecutorService refCountingPool, Set<EventType> asyncTypes, String name)
+ public PoolingFilter(ReferenceCountingExecutorService refCountingPool, String name)
{
_poolReference = refCountingPool;
- _asyncTypes = asyncTypes;
_name = name;
}
- private void fireEvent(IoSession session, Event event)
+ void fireAsynchEvent(IoSession session, Event event)
{
- if (_asyncTypes.contains(event.getType()))
- {
- Job job = getJobForSession(session);
- job.acquire(); //prevents this job being removed from _jobs
- job.add(event);
+ Job job = getJobForSession(session);
+ // job.acquire(); //prevents this job being removed from _jobs
+ job.add(event);
- //Additional checks on pool to check that it hasn't shutdown.
- // The alternative is to catch the RejectedExecutionException that will result from executing on a shutdown pool
- if (job.activate() && _poolReference.getPool() != null && !_poolReference.getPool().isShutdown())
- {
- _poolReference.getPool().execute(job);
- }
- }
- else
+ //Additional checks on pool to check that it hasn't shutdown.
+ // The alternative is to catch the RejectedExecutionException that will result from executing on a shutdown pool
+ if (job.activate() && _poolReference.getPool() != null && !_poolReference.getPool().isShutdown())
{
- event.process(session);
+ _poolReference.getPool().execute(job);
}
+
+ }
+
+ public void createNewJobForSession(IoSession session)
+ {
+ Job job = new Job(session, this, _maxEvents);
+ session.setAttribute(_name, job);
}
private Job getJobForSession(IoSession session)
{
- Job job = _jobs.get(session);
- return job == null ? createJobForSession(session) : job;
+ return (Job) session.getAttribute(_name);
+
+/* if(job == null)
+ {
+ System.err.println("Error in " + _name);
+ Thread.dumpStack();
+ }
+
+
+ job = _jobs.get(session);
+ return job == null ? createJobForSession(session) : job;*/
}
private Job createJobForSession(IoSession session)
@@ -93,15 +96,16 @@ public class PoolingFilter extends IoFilterAdapter implements Job.JobCompletionH
//Job.JobCompletionHandler
public void completed(IoSession session, Job job)
{
- if (job.isComplete())
- {
- job.release();
- if (!job.isReferenced())
- {
- _jobs.remove(session);
- }
- }
- else
+// if (job.isComplete())
+// {
+// job.release();
+// if (!job.isReferenced())
+// {
+// _jobs.remove(session);
+// }
+// }
+// else
+ if(!job.isComplete())
{
// ritchiem : 2006-12-13 Do we need to perform the additional checks here?
// Can the pool be shutdown at this point?
@@ -114,45 +118,44 @@ public class PoolingFilter extends IoFilterAdapter implements Job.JobCompletionH
//IoFilter methods that are processed by threads on the pool
- public void sessionOpened(NextFilter nextFilter, IoSession session) throws Exception
+ public void sessionOpened(final NextFilter nextFilter, final IoSession session) throws Exception
{
- fireEvent(session, new Event(nextFilter, EventType.OPENED, null));
+ nextFilter.sessionOpened(session);
}
- public void sessionClosed(NextFilter nextFilter, IoSession session) throws Exception
+ public void sessionClosed(final NextFilter nextFilter, final IoSession session) throws Exception
{
- fireEvent(session, new Event(nextFilter, EventType.CLOSED, null));
+ nextFilter.sessionClosed(session);
}
- public void sessionIdle(NextFilter nextFilter, IoSession session,
- IdleStatus status) throws Exception
+ public void sessionIdle(final NextFilter nextFilter, final IoSession session,
+ final IdleStatus status) throws Exception
{
- fireEvent(session, new Event(nextFilter, EventType.IDLE, status));
+ nextFilter.sessionIdle(session, status);
}
- public void exceptionCaught(NextFilter nextFilter, IoSession session,
- Throwable cause) throws Exception
+ public void exceptionCaught(final NextFilter nextFilter, final IoSession session,
+ final Throwable cause) throws Exception
{
- fireEvent(session, new Event(nextFilter, EventType.EXCEPTION, cause));
+ nextFilter.exceptionCaught(session,cause);
}
- public void messageReceived(NextFilter nextFilter, IoSession session,
- Object message) throws Exception
+ public void messageReceived(final NextFilter nextFilter, final IoSession session,
+ final Object message) throws Exception
{
- //ByteBufferUtil.acquireIfPossible( message );
- fireEvent(session, new Event(nextFilter, EventType.RECEIVED, message));
+ nextFilter.messageReceived(session,message);
}
- public void messageSent(NextFilter nextFilter, IoSession session,
- Object message) throws Exception
+ public void messageSent(final NextFilter nextFilter, final IoSession session,
+ final Object message) throws Exception
{
- //ByteBufferUtil.acquireIfPossible( message );
- fireEvent(session, new Event(nextFilter, EventType.SENT, message));
+ nextFilter.messageSent(session, message);
}
- public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws Exception
+ public void filterWrite(final NextFilter nextFilter, final IoSession session,
+ final WriteRequest writeRequest) throws Exception
{
- fireEvent(session, new Event(nextFilter, EventType.WRITE, writeRequest));
+ nextFilter.filterWrite(session, writeRequest);
}
//IoFilter methods that are processed on current thread (NOT on pooled thread)
@@ -188,5 +191,51 @@ public class PoolingFilter extends IoFilterAdapter implements Job.JobCompletionH
// when the reference count gets to zero we release the executor service
_poolReference.releaseExecutorService();
}
+
+ public static class AsynchReadPoolingFilter extends PoolingFilter
+ {
+
+ public AsynchReadPoolingFilter(ReferenceCountingExecutorService refCountingPool, String name)
+ {
+ super(refCountingPool, name);
+ }
+
+ public void messageReceived(final NextFilter nextFilter, final IoSession session,
+ final Object message) throws Exception
+ {
+ fireAsynchEvent(session, new Event.ReceivedEvent(nextFilter, message));
+ }
+
+
+ }
+
+ public static class AsynchWritePoolingFilter extends PoolingFilter
+ {
+
+ public AsynchWritePoolingFilter(ReferenceCountingExecutorService refCountingPool, String name)
+ {
+ super(refCountingPool, name);
+ }
+
+
+ public void filterWrite(final NextFilter nextFilter, final IoSession session,
+ final WriteRequest writeRequest) throws Exception
+ {
+ fireAsynchEvent(session, new Event.WriteEvent(nextFilter, writeRequest));
+ }
+
+ }
+
+ public static PoolingFilter createAynschReadPoolingFilter(ReferenceCountingExecutorService refCountingPool,String name)
+ {
+ return new AsynchReadPoolingFilter(refCountingPool,name);
+ }
+
+
+ public static PoolingFilter createAynschWritePoolingFilter(ReferenceCountingExecutorService refCountingPool,String name)
+ {
+ return new AsynchWritePoolingFilter(refCountingPool,name);
+ }
+
}
diff --git a/java/common/src/main/java/org/apache/qpid/pool/ReadWriteThreadModel.java b/java/common/src/main/java/org/apache/qpid/pool/ReadWriteThreadModel.java
index d4dbf1309a..c2f7f7ac48 100644
--- a/java/common/src/main/java/org/apache/qpid/pool/ReadWriteThreadModel.java
+++ b/java/common/src/main/java/org/apache/qpid/pool/ReadWriteThreadModel.java
@@ -26,15 +26,38 @@ import org.apache.mina.common.ThreadModel;
public class ReadWriteThreadModel implements ThreadModel
{
+
+ private static final ReadWriteThreadModel _instance = new ReadWriteThreadModel();
+
+ private final PoolingFilter _asynchronousReadFilter;
+ private final PoolingFilter _asynchronousWriteFilter;
+
+ private ReadWriteThreadModel()
+ {
+ final ReferenceCountingExecutorService executor = ReferenceCountingExecutorService.getInstance();
+ _asynchronousReadFilter = PoolingFilter.createAynschReadPoolingFilter(executor, "AsynchronousReadFilter");
+ _asynchronousWriteFilter = PoolingFilter.createAynschWritePoolingFilter(executor, "AsynchronousWriteFilter");
+ }
+
+ public PoolingFilter getAsynchronousReadFilter()
+ {
+ return _asynchronousReadFilter;
+ }
+
+ public PoolingFilter getAsynchronousWriteFilter()
+ {
+ return _asynchronousWriteFilter;
+ }
+
public void buildFilterChain(IoFilterChain chain) throws Exception
{
- ReferenceCountingExecutorService executor = ReferenceCountingExecutorService.getInstance();
- PoolingFilter asyncRead = new PoolingFilter(executor, PoolingFilter.READ_EVENTS,
- "AsynchronousReadFilter");
- PoolingFilter asyncWrite = new PoolingFilter(executor, PoolingFilter.WRITE_EVENTS,
- "AsynchronousWriteFilter");
-
- chain.addFirst("AsynchronousReadFilter", new ReferenceCountingIoFilter(asyncRead));
- chain.addLast("AsynchronousWriteFilter", new ReferenceCountingIoFilter(asyncWrite));
+
+ chain.addFirst("AsynchronousReadFilter", new ReferenceCountingIoFilter(_asynchronousReadFilter));
+ chain.addLast("AsynchronousWriteFilter", new ReferenceCountingIoFilter(_asynchronousWriteFilter));
+ }
+
+ public static ReadWriteThreadModel getInstance()
+ {
+ return _instance;
}
}
diff --git a/java/common/src/main/java/org/apache/qpid/protocol/AMQConstant.java b/java/common/src/main/java/org/apache/qpid/protocol/AMQConstant.java
index 8ea0d6ef1a..523a24f278 100644
--- a/java/common/src/main/java/org/apache/qpid/protocol/AMQConstant.java
+++ b/java/common/src/main/java/org/apache/qpid/protocol/AMQConstant.java
@@ -20,6 +20,8 @@
*/
package org.apache.qpid.protocol;
+import org.apache.qpid.framing.AMQShortString;
+
import java.util.Map;
import java.util.HashMap;
@@ -27,14 +29,14 @@ public final class AMQConstant
{
private int _code;
- private String _name;
+ private AMQShortString _name;
private static Map _codeMap = new HashMap();
private AMQConstant(int code, String name, boolean map)
{
_code = code;
- _name = name;
+ _name = new AMQShortString(name);
if (map)
{
_codeMap.put(new Integer(code), this);
@@ -51,7 +53,7 @@ public final class AMQConstant
return _code;
}
- public String getName()
+ public AMQShortString getName()
{
return _name;
}
diff --git a/java/common/src/main/java/org/apache/qpid/protocol/AMQVersionAwareProtocolSession.java b/java/common/src/main/java/org/apache/qpid/protocol/AMQVersionAwareProtocolSession.java
new file mode 100644
index 0000000000..a2d3de2f9e
--- /dev/null
+++ b/java/common/src/main/java/org/apache/qpid/protocol/AMQVersionAwareProtocolSession.java
@@ -0,0 +1,29 @@
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+package org.apache.qpid.protocol;
+
+import org.apache.qpid.framing.AMQDataBlock;
+import org.apache.qpid.framing.VersionSpecificRegistry;
+
+public interface AMQVersionAwareProtocolSession extends AMQProtocolWriter, ProtocolVersionAware
+{
+ public VersionSpecificRegistry getRegistry();
+}
diff --git a/java/common/src/main/java/org/apache/qpid/protocol/ProtocolVersionAware.java b/java/common/src/main/java/org/apache/qpid/protocol/ProtocolVersionAware.java
new file mode 100644
index 0000000000..cbd8b900f3
--- /dev/null
+++ b/java/common/src/main/java/org/apache/qpid/protocol/ProtocolVersionAware.java
@@ -0,0 +1,30 @@
+/*
+ *
+ * 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.protocol;
+
+public interface ProtocolVersionAware
+{
+ public byte getProtocolMinorVersion();
+
+ public byte getProtocolMajorVersion();
+
+ public boolean isProtocolVersionEqual(byte majorVersion, byte minorVersion);
+}
diff --git a/java/common/src/main/java/org/apache/qpid/url/AMQBindingURL.java b/java/common/src/main/java/org/apache/qpid/url/AMQBindingURL.java
index b6a0bd500a..11e6652bd7 100644
--- a/java/common/src/main/java/org/apache/qpid/url/AMQBindingURL.java
+++ b/java/common/src/main/java/org/apache/qpid/url/AMQBindingURL.java
@@ -23,6 +23,7 @@ package org.apache.qpid.url;
import org.apache.qpid.url.BindingURL;
import org.apache.qpid.url.URLHelper;
import org.apache.qpid.exchange.ExchangeDefaults;
+import org.apache.qpid.framing.AMQShortString;
import java.util.HashMap;
import java.net.URI;
@@ -31,10 +32,10 @@ import java.net.URISyntaxException;
public class AMQBindingURL implements BindingURL
{
String _url;
- String _exchangeClass;
- String _exchangeName;
- String _destinationName;
- String _queueName;
+ AMQShortString _exchangeClass;
+ AMQShortString _exchangeName;
+ AMQShortString _destinationName;
+ AMQShortString _queueName;
private HashMap<String, String> _options;
@@ -84,7 +85,7 @@ public class AMQBindingURL implements BindingURL
if (connection.getPath() == null ||
connection.getPath().equals(""))
{
- URLHelper.parseError(_url.indexOf(_exchangeName) + _exchangeName.length(),
+ URLHelper.parseError(_url.indexOf(_exchangeName.toString()) + _exchangeName.length(),
"Destination or Queue requried", _url);
}
else
@@ -92,7 +93,7 @@ public class AMQBindingURL implements BindingURL
int slash = connection.getPath().indexOf("/", 1);
if (slash == -1)
{
- URLHelper.parseError(_url.indexOf(_exchangeName) + _exchangeName.length(),
+ URLHelper.parseError(_url.indexOf(_exchangeName.toString()) + _exchangeName.length(),
"Destination requried", _url);
}
else
@@ -121,6 +122,26 @@ public class AMQBindingURL implements BindingURL
}
}
+ private void setExchangeClass(String exchangeClass)
+ {
+ setExchangeClass(new AMQShortString(exchangeClass));
+ }
+
+ private void setQueueName(String name)
+ {
+ setQueueName(new AMQShortString(name));
+ }
+
+ private void setDestinationName(String name)
+ {
+ setDestinationName(new AMQShortString(name));
+ }
+
+ private void setExchangeName(String exchangeName)
+ {
+ setExchangeName(new AMQShortString(exchangeName));
+ }
+
private void processOptions()
{
//this is where we would parse any options that needed more than just storage.
@@ -131,22 +152,22 @@ public class AMQBindingURL implements BindingURL
return _url;
}
- public String getExchangeClass()
+ public AMQShortString getExchangeClass()
{
return _exchangeClass;
}
- public void setExchangeClass(String exchangeClass)
+ public void setExchangeClass(AMQShortString exchangeClass)
{
_exchangeClass = exchangeClass;
}
- public String getExchangeName()
+ public AMQShortString getExchangeName()
{
return _exchangeName;
}
- public void setExchangeName(String name)
+ public void setExchangeName(AMQShortString name)
{
_exchangeName = name;
@@ -156,17 +177,17 @@ public class AMQBindingURL implements BindingURL
}
}
- public String getDestinationName()
+ public AMQShortString getDestinationName()
{
return _destinationName;
}
- public void setDestinationName(String name)
+ public void setDestinationName(AMQShortString name)
{
_destinationName = name;
}
- public String getQueueName()
+ public AMQShortString getQueueName()
{
if (_exchangeClass.equals(ExchangeDefaults.TOPIC_EXCHANGE_CLASS))
{
@@ -174,7 +195,7 @@ public class AMQBindingURL implements BindingURL
{
if (containsOption(BindingURL.OPTION_CLIENTID) && containsOption(BindingURL.OPTION_SUBSCRIPTION))
{
- return getOption(BindingURL.OPTION_CLIENTID + ":" + BindingURL.OPTION_SUBSCRIPTION);
+ return new AMQShortString(getOption(BindingURL.OPTION_CLIENTID + ":" + BindingURL.OPTION_SUBSCRIPTION));
}
else
{
@@ -192,7 +213,7 @@ public class AMQBindingURL implements BindingURL
}
}
- public void setQueueName(String name)
+ public void setQueueName(AMQShortString name)
{
_queueName = name;
}
@@ -212,7 +233,7 @@ public class AMQBindingURL implements BindingURL
return _options.containsKey(key);
}
- public String getRoutingKey()
+ public AMQShortString getRoutingKey()
{
if (_exchangeClass.equals(ExchangeDefaults.DIRECT_EXCHANGE_CLASS))
{
@@ -221,15 +242,15 @@ public class AMQBindingURL implements BindingURL
if (containsOption(BindingURL.OPTION_ROUTING_KEY))
{
- return getOption(OPTION_ROUTING_KEY);
+ return new AMQShortString(getOption(OPTION_ROUTING_KEY));
}
return getDestinationName();
}
- public void setRoutingKey(String key)
+ public void setRoutingKey(AMQShortString key)
{
- setOption(OPTION_ROUTING_KEY, key);
+ setOption(OPTION_ROUTING_KEY, key.toString());
}
diff --git a/java/common/src/main/java/org/apache/qpid/url/BindingURL.java b/java/common/src/main/java/org/apache/qpid/url/BindingURL.java
index 76690b3230..86a8420d30 100644
--- a/java/common/src/main/java/org/apache/qpid/url/BindingURL.java
+++ b/java/common/src/main/java/org/apache/qpid/url/BindingURL.java
@@ -20,6 +20,8 @@
*/
package org.apache.qpid.url;
+import org.apache.qpid.framing.AMQShortString;
+
/*
Binding URL format:
<exch_class>://<exch_name>/[<destination>]/[<queue>]?<option>='<value>'[,<option>='<value>']*
@@ -36,21 +38,21 @@ public interface BindingURL
String getURL();
- String getExchangeClass();
+ AMQShortString getExchangeClass();
- void setExchangeClass(String exchangeClass);
+ void setExchangeClass(AMQShortString name);
- String getExchangeName();
+ AMQShortString getExchangeName();
- void setExchangeName(String name);
+ void setExchangeName(AMQShortString name);
- String getDestinationName();
+ AMQShortString getDestinationName();
- void setDestinationName(String name);
+ void setDestinationName(AMQShortString name);
- String getQueueName();
+ AMQShortString getQueueName();
- void setQueueName(String name);
+ void setQueueName(AMQShortString name);
String getOption(String key);
@@ -58,9 +60,9 @@ public interface BindingURL
boolean containsOption(String key);
- String getRoutingKey();
+ AMQShortString getRoutingKey();
- void setRoutingKey(String key);
+ void setRoutingKey(AMQShortString key);
String toString();
}
diff --git a/java/common/src/main/java/org/apache/qpid/util/concurrent/BooleanLatch.java b/java/common/src/main/java/org/apache/qpid/util/concurrent/BooleanLatch.java
new file mode 100644
index 0000000000..70a5f2dc5e
--- /dev/null
+++ b/java/common/src/main/java/org/apache/qpid/util/concurrent/BooleanLatch.java
@@ -0,0 +1,42 @@
+/*
+ *
+ * Copyright (c) 2006 The Apache Software Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+package org.apache.qpid.util.concurrent;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * @author Apache Software Foundation
+ */
+public class BooleanLatch extends CountDownLatch
+{
+ public BooleanLatch()
+ {
+ super(1);
+ }
+
+ public void signal()
+ {
+ countDown();
+ }
+
+ public void await(long nanos) throws InterruptedException
+ {
+ await(nanos, TimeUnit.NANOSECONDS);
+ }
+}
diff --git a/java/common/src/test/java/org/apache/qpid/framing/JMSPropertyFieldTableTest.java b/java/common/src/test/java/org/apache/qpid/framing/JMSPropertyFieldTableTest.java
deleted file mode 100644
index 94c97ef808..0000000000
--- a/java/common/src/test/java/org/apache/qpid/framing/JMSPropertyFieldTableTest.java
+++ /dev/null
@@ -1,1016 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- *
- */
-package org.apache.qpid.framing;
-
-import junit.framework.Assert;
-import junit.framework.TestCase;
-
-import java.util.Enumeration;
-
-import org.apache.log4j.Logger;
-
-import javax.jms.JMSException;
-import javax.jms.MessageFormatException;
-
-public class JMSPropertyFieldTableTest extends TestCase
-{
-
- private static final Logger _logger = Logger.getLogger(JMSPropertyFieldTableTest.class);
-
-
- public void setUp()
- {
- System.getProperties().setProperty("strict-jms", "true");
- }
-
- public void tearDown()
- {
- System.getProperties().remove("strict-jms");
- }
-
- /**
- * Test that setting a similar named value replaces any previous value set on that name
- */
- public void testReplacement() throws JMSException
- {
- JMSPropertyFieldTable table1 = new JMSPropertyFieldTable(new FieldTable());
- //Set a boolean value
- table1.setBoolean("value", true);
-
- // reset value to an integer
- table1.setInteger("value", Integer.MAX_VALUE);
-
- //Check boolean value is null
- try
- {
- table1.getBoolean("value");
- }
- catch (MessageFormatException mfe)
- {
- //normal execution
- }
- // ... and integer value is good
- Assert.assertEquals(Integer.MAX_VALUE, table1.getInteger("value"));
- }
-
- public void testRemoval() throws JMSException
- {
- JMSPropertyFieldTable table1 = new JMSPropertyFieldTable(new FieldTable());
- //Set a boolean value
- table1.setBoolean("value", true);
-
- Assert.assertTrue(table1.getBoolean("value"));
-
- table1.remove("value");
-
- //Check boolean value is null
- try
- {
- table1.getBoolean("value");
- }
- catch (MessageFormatException mfe)
- {
- //normal execution
- }
- }
-
-
- /**
- * Set a boolean and check that we can only get it back as a boolean and a string
- * Check that attempting to lookup a non existent value returns null
- */
- public void testBoolean() throws JMSException
- {
- JMSPropertyFieldTable table1 = new JMSPropertyFieldTable(new FieldTable());
- table1.setBoolean("value", true);
- Assert.assertTrue(table1.propertyExists("value"));
-
- //Test Getting right value back
- Assert.assertEquals(true, table1.getBoolean("value"));
-
- //Check we don't get anything back for other gets
- try
- {
- table1.getByte("value");
- fail("Should throw MessageFormatException");
- }
- catch (MessageFormatException mfs)
- {
- //normal Execution
- }
-
- try
- {
- table1.getByte("value");
- fail("Should throw MessageFormatException");
- }
- catch (MessageFormatException mfs)
- {
- //normal Execution
- }
-
- try
- {
- table1.getShort("value");
- fail("Should throw MessageFormatException");
- }
- catch (MessageFormatException mfs)
- {
- //normal Execution
- }
-
- try
- {
- table1.getDouble("value");
- fail("Should throw MessageFormatException");
- }
- catch (MessageFormatException mfs)
- {
- //normal Execution
- }
-
- try
- {
- table1.getFloat("value");
- fail("Should throw MessageFormatException");
- }
- catch (MessageFormatException mfs)
- {
- //normal Execution
- }
-
- try
- {
- table1.getInteger("value");
- fail("Should throw MessageFormatException");
- }
- catch (MessageFormatException mfs)
- {
- //normal Execution
- }
-
- try
- {
- table1.getLong("value");
- fail("Should throw MessageFormatException");
- }
- catch (MessageFormatException mfs)
- {
- //normal Execution
- }
-
- //except value as a string
- Assert.assertEquals("true", table1.getString("value"));
-
- table1.remove("value");
- //but after a remove it doesn't
- Assert.assertFalse(table1.propertyExists("value"));
-
- // Table should now have zero length for encoding
- checkEmpty(table1);
-
- //Looking up an invalid value will return false
- Assert.assertFalse(table1.getBoolean("Rubbish"));
- }
-
- /**
- * Set a byte and check that we can only get it back as a byte and a string
- * Check that attempting to lookup a non existent value returns null
- */
- public void testByte() throws JMSException
- {
- JMSPropertyFieldTable table1 = new JMSPropertyFieldTable(new FieldTable());
- table1.setByte("value", Byte.MAX_VALUE);
- Assert.assertTrue(table1.propertyExists("value"));
-
- //Tets lookups we shouldn't get anything back for other gets
- //we should get right value back for this type ....
- try
- {
- table1.getBoolean("value");
- fail("Should throw MessageFormatException");
- }
- catch (MessageFormatException mfs)
- {
- //normal Execution
- }
-
- try
- {
- table1.getDouble("value");
- fail("Should throw MessageFormatException");
- }
- catch (MessageFormatException mfs)
- {
- //normal Execution
- }
- try
- {
- table1.getFloat("value");
- fail("Should throw MessageFormatException");
- }
- catch (MessageFormatException mfs)
- {
- //normal Execution
- }
-
- Assert.assertEquals(Byte.MAX_VALUE, (byte) table1.getShort("value"));
- Assert.assertEquals(Byte.MAX_VALUE, (byte) table1.getInteger("value"));
- Assert.assertEquals(Byte.MAX_VALUE, (byte) table1.getLong("value"));
- Assert.assertEquals(Byte.MAX_VALUE, table1.getByte("value"));
- //... and a the string value of it.
- Assert.assertEquals("" + Byte.MAX_VALUE, table1.getString("value"));
-
- table1.remove("value");
- //but after a remove it doesn't
- Assert.assertFalse(table1.propertyExists("value"));
-
- // Table should now have zero length for encoding
- checkEmpty(table1);
-
- //Looking up an invalid value returns null
- try
- {
- table1.getByte("Rubbish");
- fail("Should throw NumberFormatException");
- }
- catch (NumberFormatException mfs)
- {
- //normal Execution
- }
-
- }
-
-
- /**
- * Set a short and check that we can only get it back as a short and a string
- * Check that attempting to lookup a non existent value returns null
- */
- public void testShort() throws JMSException
- {
- JMSPropertyFieldTable table1 = new JMSPropertyFieldTable(new FieldTable());
- table1.setShort("value", Short.MAX_VALUE);
- Assert.assertTrue(table1.propertyExists("value"));
-
- //Tets lookups we shouldn't get anything back for other gets
- //we should get right value back for this type ....
-
- try
- {
- table1.getBoolean("value");
- fail("Should throw MessageFormatException");
- }
- catch (MessageFormatException mfs)
- {
- //normal Execution
- }
- try
- {
- table1.getByte("value");
- fail("Should throw MessageFormatException");
- }
- catch (MessageFormatException mfs)
- {
- //normal Execution
- }
-
- try
- {
- table1.getDouble("value");
- fail("Should throw MessageFormatException");
- }
- catch (MessageFormatException mfs)
- {
- //normal Execution
- }
- try
- {
- table1.getFloat("value");
- fail("Should throw MessageFormatException");
- }
- catch (MessageFormatException mfs)
- {
- //normal Execution
- }
-
-
- Assert.assertEquals(Short.MAX_VALUE, (short) table1.getLong("value"));
- Assert.assertEquals(Short.MAX_VALUE, (short) table1.getInteger("value"));
- Assert.assertEquals(Short.MAX_VALUE, table1.getShort("value"));
-
- //... and a the string value of it.
- Assert.assertEquals("" + Short.MAX_VALUE, table1.getString("value"));
-
- table1.remove("value");
- //but after a remove it doesn't
- Assert.assertFalse(table1.propertyExists("value"));
-
- // Table should now have zero length for encoding
- checkEmpty(table1);
-
- //Looking up an invalid value returns null
- try
- {
- table1.getShort("Rubbish");
- fail("Should throw NumberFormatException");
- }
- catch (NumberFormatException mfe)
- {
- //normal path
- }
- }
-
-
- /**
- * Set a double and check that we can only get it back as a double
- * Check that attempting to lookup a non existent value returns null
- */
- public void testDouble() throws JMSException
- {
- JMSPropertyFieldTable table1 = new JMSPropertyFieldTable(new FieldTable());
- table1.setDouble("value", Double.MAX_VALUE);
- Assert.assertTrue(table1.propertyExists("value"));
-
- //Tets lookups we shouldn't get anything back for other gets
- //we should get right value back for this type ....
- try
- {
- table1.getBoolean("value");
- fail("Should throw MessageFormatException");
- }
- catch (MessageFormatException mfs)
- {
- //normal Execution
- }
- try
- {
- table1.getByte("value");
- fail("Should throw MessageFormatException");
- }
- catch (MessageFormatException mfs)
- {
- //normal Execution
- }
- try
- {
- table1.getShort("value");
- fail("Should throw MessageFormatException");
- }
- catch (MessageFormatException mfs)
- {
- //normal Execution
- }
- try
- {
- table1.getFloat("value");
- fail("Should throw MessageFormatException");
- }
- catch (MessageFormatException mfs)
- {
- //normal Execution
- }
- try
- {
- table1.getInteger("value");
- fail("Should throw MessageFormatException");
- }
- catch (MessageFormatException mfs)
- {
- //normal Execution
- }
- try
- {
- table1.getLong("value");
- fail("Should throw MessageFormatException");
- }
- catch (MessageFormatException mfs)
- {
- //normal Execution
- }
-
- Assert.assertEquals(Double.MAX_VALUE, table1.getDouble("value"));
- //... and a the string value of it.
- Assert.assertEquals("" + Double.MAX_VALUE, table1.getString("value"));
-
- table1.remove("value");
- //but after a remove it doesn't
- Assert.assertFalse(table1.propertyExists("value"));
-
- // Table should now have zero length for encoding
- checkEmpty(table1);
-
- //Looking up an invalid value returns null
- try
- {
- table1.getDouble("Rubbish");
- fail("Should throw NullPointerException as float.valueOf will try sunreadJavaFormatString");
- }
- catch (NullPointerException mfe)
- {
- //normal path
- }
-
- }
-
-
- /**
- * Set a float and check that we can only get it back as a float
- * Check that attempting to lookup a non existent value returns null
- */
- public void testFloat() throws JMSException
- {
- JMSPropertyFieldTable table1 = new JMSPropertyFieldTable(new FieldTable());
- table1.setFloat("value", Float.MAX_VALUE);
- Assert.assertTrue(table1.propertyExists("value"));
-
- //Tets lookups we shouldn't get anything back for other gets
- //we should get right value back for this type ....
- try
- {
- table1.getBoolean("value");
- fail("Should throw MessageFormatException");
- }
- catch (MessageFormatException mfs)
- {
- //normal Execution
- }
- try
- {
- table1.getByte("value");
- fail("Should throw MessageFormatException");
- }
- catch (MessageFormatException mfs)
- {
- //normal Execution
- }
- try
- {
- table1.getShort("value");
- fail("Should throw MessageFormatException");
- }
- catch (MessageFormatException mfs)
- {
- //normal Execution
- }
- try
- {
- table1.getInteger("value");
- fail("Should throw MessageFormatException");
- }
- catch (MessageFormatException mfs)
- {
- //normal Execution
- }
- try
- {
- table1.getLong("value");
- fail("Should throw MessageFormatException");
- }
- catch (MessageFormatException mfs)
- {
- //normal Execution
- }
-
-
- Assert.assertEquals(Float.MAX_VALUE, table1.getFloat("value"));
- Assert.assertEquals(Float.MAX_VALUE, (float) table1.getDouble("value"));
-
- //... and a the string value of it.
- Assert.assertEquals("" + Float.MAX_VALUE, table1.getString("value"));
-
- table1.remove("value");
- //but after a remove it doesn't
- Assert.assertFalse(table1.propertyExists("value"));
-
- // Table should now have zero length for encoding
- checkEmpty(table1);
-
- //Looking up an invalid value returns null
- try
- {
- table1.getFloat("Rubbish");
- fail("Should throw NullPointerException as float.valueOf will try sunreadJavaFormatString");
- }
- catch (NullPointerException mfe)
- {
- //normal path
- }
- }
-
-
- /**
- * Set an int and check that we can only get it back as an int
- * Check that attempting to lookup a non existent value returns null
- */
- public void testInt() throws JMSException
- {
- JMSPropertyFieldTable table1 = new JMSPropertyFieldTable(new FieldTable());
- table1.setInteger("value", Integer.MAX_VALUE);
- Assert.assertTrue(table1.propertyExists("value"));
-
- //Tets lookups we shouldn't get anything back for other gets
- //we should get right value back for this type ....
- try
- {
- table1.getBoolean("value");
- fail("Should throw MessageFormatException");
- }
- catch (MessageFormatException mfs)
- {
- //normal Execution
- }
- try
- {
- table1.getByte("value");
- fail("Should throw MessageFormatException");
- }
- catch (MessageFormatException mfs)
- {
- //normal Execution
- }
- try
- {
- table1.getShort("value");
- fail("Should throw MessageFormatException");
- }
- catch (MessageFormatException mfs)
- {
- //normal Execution
- }
- try
- {
- table1.getDouble("value");
- fail("Should throw MessageFormatException");
- }
- catch (MessageFormatException mfs)
- {
- //normal Execution
- }
- try
- {
- table1.getFloat("value");
- fail("Should throw MessageFormatException");
- }
- catch (MessageFormatException mfs)
- {
- //normal Execution
- }
-
-
- Assert.assertEquals(Integer.MAX_VALUE, table1.getLong("value"));
-
- Assert.assertEquals(Integer.MAX_VALUE, table1.getInteger("value"));
-
- //... and a the string value of it.
- Assert.assertEquals("" + Integer.MAX_VALUE, table1.getString("value"));
-
- table1.remove("value");
- //but after a remove it doesn't
- Assert.assertFalse(table1.propertyExists("value"));
-
- // Table should now have zero length for encoding
- checkEmpty(table1);
-
- //Looking up an invalid value returns null
- try
- {
- table1.getInteger("Rubbish");
- fail("Should throw NumberFormatException");
- }
- catch (NumberFormatException mfe)
- {
- //normal path
- }
- }
-
-
- /**
- * Set a long and check that we can only get it back as a long
- * Check that attempting to lookup a non existent value returns null
- */
- public void testLong() throws JMSException
- {
- JMSPropertyFieldTable table1 = new JMSPropertyFieldTable(new FieldTable());
- table1.setLong("value", Long.MAX_VALUE);
- Assert.assertTrue(table1.propertyExists("value"));
-
- //Tets lookups we shouldn't get anything back for other gets
- //we should get right value back for this type ....
- try
- {
- table1.getBoolean("value");
- fail("Should throw MessageFormatException");
- }
- catch (MessageFormatException mfs)
- {
- //normal Execution
- }
- try
- {
- table1.getByte("value");
- fail("Should throw MessageFormatException");
- }
- catch (MessageFormatException mfs)
- {
- //normal Execution
- }
- try
- {
- table1.getShort("value");
- fail("Should throw MessageFormatException");
- }
- catch (MessageFormatException mfs)
- {
- //normal Execution
- }
- try
- {
- table1.getDouble("value");
- fail("Should throw MessageFormatException");
- }
- catch (MessageFormatException mfs)
- {
- //normal Execution
- }
- try
- {
- table1.getFloat("value");
- fail("Should throw MessageFormatException");
- }
- catch (MessageFormatException mfs)
- {
- //normal Execution
- }
- try
- {
- table1.getInteger("value");
- fail("Should throw MessageFormatException");
- }
- catch (MessageFormatException mfs)
- {
- //normal Execution
- }
-
-
- Assert.assertEquals(Long.MAX_VALUE, table1.getLong("value"));
-
- //... and a the string value of it.
- Assert.assertEquals("" + Long.MAX_VALUE, table1.getString("value"));
-
- table1.remove("value");
- //but after a remove it doesn't
- Assert.assertFalse(table1.propertyExists("value"));
-
- // Table should now have zero length for encoding
- checkEmpty(table1);
-
- //Looking up an invalid value
- try
- {
- table1.getLong("Rubbish");
- fail("Should throw NumberFormatException");
- }
- catch (NumberFormatException mfs)
- {
- //normal Execution
- }
-
- }
-
-
- /**
- * Calls all methods that can be used to check the table is empty
- * - getEncodedSize
- * - isEmpty
- * - length
- *
- * @param table to check is empty
- */
- private void checkEmpty(JMSPropertyFieldTable table)
- {
- Assert.assertFalse(table.getPropertyNames().hasMoreElements());
- }
-
-
- /**
- * Set a String and check that we can only get it back as a String
- * Check that attempting to lookup a non existent value returns null
- */
- public void testString() throws JMSException
- {
- JMSPropertyFieldTable table1 = new JMSPropertyFieldTable(new FieldTable());
- table1.setString("value", "Hello");
- Assert.assertTrue(table1.propertyExists("value"));
-
- //Tets lookups we shouldn't get anything back for other gets
- //we should get right value back for this type ....
- Assert.assertEquals(false, table1.getBoolean("value"));
-
- try
- {
- table1.getByte("value");
- fail("Should throw NumberFormatException");
- }
- catch (NumberFormatException nfs)
- {
- //normal Execution
- }
- try
- {
- table1.getShort("value");
- fail("Should throw NumberFormatException");
- }
- catch (NumberFormatException nfs)
- {
- //normal Execution
- }
- try
- {
- table1.getDouble("value");
- fail("Should throw NumberFormatException");
- }
- catch (NumberFormatException nfs)
- {
- //normal Execution
- }
- try
- {
- table1.getFloat("value");
- fail("Should throw NumberFormatException");
- }
- catch (NumberFormatException nfs)
- {
- //normal Execution
- }
- try
- {
- table1.getInteger("value");
- fail("Should throw NumberFormatException");
- }
- catch (NumberFormatException nfs)
- {
- //normal Execution
- }
- try
- {
- table1.getLong("value");
- fail("Should throw NumberFormatException");
- }
- catch (NumberFormatException nfs)
- {
- //normal Execution
- }
-
- Assert.assertEquals("Hello", table1.getString("value"));
-
- table1.remove("value");
- //but after a remove it doesn't
- Assert.assertFalse(table1.propertyExists("value"));
-
- checkEmpty(table1);
-
- //Looking up an invalid value returns null
- Assert.assertEquals(null, table1.getString("Rubbish"));
-
- //Additional Test that haven't been covered for string
- table1.setObject("value", "Hello");
- //Check that it was set correctly
- Assert.assertEquals("Hello", table1.getString("value"));
- }
-
-
- public void testValues() throws JMSException
- {
- JMSPropertyFieldTable table = new JMSPropertyFieldTable(new FieldTable());
- table.setBoolean("bool", true);
- table.setDouble("double", Double.MAX_VALUE);
- table.setFloat("float", Float.MAX_VALUE);
- table.setInteger("int", Integer.MAX_VALUE);
- table.setLong("long", Long.MAX_VALUE);
- table.setShort("short", Short.MAX_VALUE);
- table.setString("string", "Hello");
- table.setString("nullstring", null);
-
- table.setObject("objectbool", true);
- table.setObject("objectdouble", Double.MAX_VALUE);
- table.setObject("objectfloat", Float.MAX_VALUE);
- table.setObject("objectint", Integer.MAX_VALUE);
- table.setObject("objectlong", Long.MAX_VALUE);
- table.setObject("objectshort", Short.MAX_VALUE);
- table.setObject("objectstring", "Hello");
-
-
- Assert.assertEquals(true, table.getBoolean("bool"));
-
- Assert.assertEquals(Double.MAX_VALUE, table.getDouble("double"));
- Assert.assertEquals(Float.MAX_VALUE, table.getFloat("float"));
- Assert.assertEquals(Integer.MAX_VALUE, table.getInteger("int"));
- Assert.assertEquals(Long.MAX_VALUE, table.getLong("long"));
- Assert.assertEquals(Short.MAX_VALUE, table.getShort("short"));
- Assert.assertEquals("Hello", table.getString("string"));
- Assert.assertEquals(null, table.getString("null-string"));
-
- Assert.assertEquals(true, table.getObject("objectbool"));
- Assert.assertEquals(Double.MAX_VALUE, table.getObject("objectdouble"));
- Assert.assertEquals(Float.MAX_VALUE, table.getObject("objectfloat"));
- Assert.assertEquals(Integer.MAX_VALUE, table.getObject("objectint"));
- Assert.assertEquals(Long.MAX_VALUE, table.getObject("objectlong"));
- Assert.assertEquals(Short.MAX_VALUE, table.getObject("objectshort"));
- Assert.assertEquals("Hello", table.getObject("objectstring"));
- }
-
- /**
- * Additional test checkPropertyName doesn't accept Null
- */
- public void testCheckPropertyNameasNull() throws JMSException
- {
- JMSPropertyFieldTable table = new JMSPropertyFieldTable(new FieldTable());
-
- try
- {
- table.setObject(null, "String");
- fail("Null property name is not allowed");
- }
- catch (IllegalArgumentException iae)
- {
- //normal path
- }
- checkEmpty(table);
- }
-
-
- /**
- * Additional test checkPropertyName doesn't accept an empty String
- */
- public void testCheckPropertyNameasEmptyString() throws JMSException
- {
- JMSPropertyFieldTable table = new JMSPropertyFieldTable(new FieldTable());
-
- try
- {
- table.setObject("", "String");
- fail("empty property name is not allowed");
- }
- catch (IllegalArgumentException iae)
- {
- //normal path
- }
- checkEmpty(table);
- }
-
-
- /**
- * Additional test checkPropertyName doesn't accept an empty String
- */
- public void testCheckPropertyNamehasMaxLength() throws JMSException
- {
- JMSPropertyFieldTable table = new JMSPropertyFieldTable(new FieldTable());
-
- StringBuffer longPropertyName = new StringBuffer(129);
-
- for (int i = 0; i < 129; i++)
- {
- longPropertyName.append("x");
- }
-
- try
- {
- table.setObject(longPropertyName.toString(), "String");
- fail("property name must be < 128 characters");
- }
- catch (IllegalArgumentException iae)
- {
- _logger.warn("JMS requires infinite property names AMQP limits us to 128 characters");
- }
-
- checkEmpty(table);
- }
-
-
- /**
- * Additional test checkPropertyName starts with a letter
- */
- public void testCheckPropertyNameStartCharacterIsLetter() throws JMSException
- {
- JMSPropertyFieldTable table = new JMSPropertyFieldTable(new FieldTable());
-
- //Try a name that starts with a number
- try
- {
- table.setObject("1", "String");
- fail("property name must start with a letter");
- }
- catch (IllegalArgumentException iae)
- {
- //normal path
- }
-
- checkEmpty(table);
- }
-
- /**
- * Additional test checkPropertyName starts with a letter
- */
- public void testCheckPropertyNameContainsInvalidCharacter() throws JMSException
- {
- JMSPropertyFieldTable table = new JMSPropertyFieldTable(new FieldTable());
-
- //Try a name that starts with a number
- try
- {
- table.setObject("hello there", "String");
- fail("property name cannot contain spaces");
- }
- catch (IllegalArgumentException iae)
- {
- //normal path
- }
-
- checkEmpty(table);
- }
-
-
- /**
- * Additional test checkPropertyName starts with a letter
- */
- public void testCheckPropertyNameIsInvalid() throws JMSException
- {
- JMSPropertyFieldTable table = new JMSPropertyFieldTable(new FieldTable());
-
- //Try a name that starts with a number
- try
- {
- table.setObject("ESCAPE", "String");
- fail("property name must not contains spaces");
- }
- catch (IllegalArgumentException iae)
- {
- //normal path
- }
-
- checkEmpty(table);
- }
-
- /**
- * Additional test checkPropertyName starts with a hash or a dollar
- */
- public void testCheckPropertyNameStartCharacterIsHashorDollar() throws JMSException
- {
- _logger.warn("Test:testCheckPropertyNameStartCharacterIsHashorDollar will fail JMS compilance as # and $ are not valid in a jms identifier");
-// JMSPropertyFieldTable table = new JMSPropertyFieldTable();
-//
-// //Try a name that starts with a number
-// try
-// {
-// table.setObject("#", "String");
-// table.setObject("$", "String");
-// }
-// catch (IllegalArgumentException iae)
-// {
-// fail("property name are allowed to start with # and $s in AMQP");
-// }
- }
-
- /**
- * Test the contents of the sets
- */
- public void testSets()
- {
-
- JMSPropertyFieldTable table = new JMSPropertyFieldTable(new FieldTable());
-
- table.put("n1", "1");
- table.put("n2", "2");
- table.put("n3", "3");
-
- Enumeration enumerator = table.getPropertyNames();
- Assert.assertEquals("n1", enumerator.nextElement());
- Assert.assertEquals("n2", enumerator.nextElement());
- Assert.assertEquals("n3", enumerator.nextElement());
- Assert.assertFalse(enumerator.hasMoreElements());
- }
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(JMSPropertyFieldTableTest.class);
- }
-
-}
diff --git a/java/common/src/test/java/org/apache/qpid/framing/PropertyFieldTableTest.java b/java/common/src/test/java/org/apache/qpid/framing/PropertyFieldTableTest.java
index c259d3ee8a..6160dc1843 100644
--- a/java/common/src/test/java/org/apache/qpid/framing/PropertyFieldTableTest.java
+++ b/java/common/src/test/java/org/apache/qpid/framing/PropertyFieldTableTest.java
@@ -25,8 +25,6 @@ import junit.framework.TestCase;
import java.util.Enumeration;
import java.util.Iterator;
-import java.util.Map;
-import java.util.HashMap;
import org.apache.mina.common.ByteBuffer;
import org.apache.log4j.Logger;
@@ -227,7 +225,7 @@ public class PropertyFieldTableTest extends TestCase
//... and a the string value of it.
Assert.assertEquals("" + Double.MAX_VALUE, table1.getString("value"));
table1.remove("value");
- //but after a remove it doesn't
+ //but after a removeKey it doesn't
Assert.assertFalse(table1.containsKey("value"));
// Table should now have zero length for encoding
@@ -265,7 +263,7 @@ public class PropertyFieldTableTest extends TestCase
table1.remove("value");
- //but after a remove it doesn't
+ //but after a removeKey it doesn't
Assert.assertFalse(table1.containsKey("value"));
// Table should now have zero length for encoding
@@ -303,7 +301,7 @@ public class PropertyFieldTableTest extends TestCase
table1.remove("value");
- //but after a remove it doesn't
+ //but after a removeKey it doesn't
Assert.assertFalse(table1.containsKey("value"));
// Table should now have zero length for encoding
@@ -341,7 +339,7 @@ public class PropertyFieldTableTest extends TestCase
table1.remove("value");
- //but after a remove it doesn't
+ //but after a removeKey it doesn't
Assert.assertFalse(table1.containsKey("value"));
// Table should now have zero length for encoding
@@ -380,7 +378,7 @@ public class PropertyFieldTableTest extends TestCase
Assert.assertEquals(null, table1.getString("value"));
table1.remove("value");
- //but after a remove it doesn't
+ //but after a removeKey it doesn't
Assert.assertFalse(table1.containsKey("value"));
// Table should now have zero length for encoding
@@ -440,7 +438,7 @@ public class PropertyFieldTableTest extends TestCase
Assert.assertTrue(table1.containsKey("value"));
table1.remove("value");
- //but after a remove it doesn't
+ //but after a removeKey it doesn't
Assert.assertFalse(table1.containsKey("value"));
checkEmpty(table1);
@@ -457,23 +455,7 @@ public class PropertyFieldTableTest extends TestCase
- public void testKeyEnumeration()
- {
- FieldTable table = new FieldTable();
- table.setLong("one", 1L);
- table.setLong("two", 2L);
- table.setLong("three", 3L);
- table.setLong("four", 4L);
- table.setLong("five", 5L);
-
- Enumeration e = table.getPropertyNames();
-
- Assert.assertTrue("one".equals(e.nextElement()));
- Assert.assertTrue("two".equals(e.nextElement()));
- Assert.assertTrue("three".equals(e.nextElement()));
- Assert.assertTrue("four".equals(e.nextElement()));
- Assert.assertTrue("five".equals(e.nextElement()));
- }
+
public void testValues()
{
@@ -546,8 +528,7 @@ public class PropertyFieldTableTest extends TestCase
table.setString("string", "hello");
table.setString("null-string", null);
-
- final ByteBuffer buffer = ByteBuffer.allocate((int) table.getEncodedSize()); // FIXME XXX: Is cast a problem?
+ final ByteBuffer buffer = ByteBuffer.allocate((int) table.getEncodedSize() + 4); // FIXME XXX: Is cast a problem?
table.writeToBuffer(buffer);
@@ -597,7 +578,7 @@ public class PropertyFieldTableTest extends TestCase
byte[] _bytes = {99, 98, 97, 96, 95};
result.setBytes("bytes", _bytes);
- size += 1 + EncodingUtils.encodedShortStringLength("bytes") + 1 + EncodingUtils.encodedByteLength() * _bytes.length;
+ size += 1 + EncodingUtils.encodedShortStringLength("bytes") + 4 + _bytes.length;
Assert.assertEquals(size, result.getEncodedSize());
result.setChar("char", (char) 'c');
@@ -639,7 +620,7 @@ public class PropertyFieldTableTest extends TestCase
Assert.assertEquals(size, result.getEncodedSize());
result.setObject("object-bytes", _bytes);
- size += 1 + EncodingUtils.encodedShortStringLength("object-bytes") + 1 + EncodingUtils.encodedByteLength() * _bytes.length;
+ size += 1 + EncodingUtils.encodedShortStringLength("object-bytes") + 4 + _bytes.length;
Assert.assertEquals(size, result.getEncodedSize());
result.setObject("object-char", 'c');
@@ -758,7 +739,7 @@ public class PropertyFieldTableTest extends TestCase
try
{
- table.setObject(null, "String");
+ table.setObject((String)null, "String");
fail("Null property name is not allowed");
}
catch (IllegalArgumentException iae)
@@ -868,9 +849,9 @@ public class PropertyFieldTableTest extends TestCase
{
FieldTable table = new FieldTable();
- table.put("StringProperty", "String");
+ table.setObject("StringProperty", "String");
- Assert.assertEquals("String", table.get("StringProperty"));
+ Assert.assertEquals("String", table.getString("StringProperty"));
//Test Clear
@@ -887,15 +868,15 @@ public class PropertyFieldTableTest extends TestCase
FieldTable table = new FieldTable();
- table.put("n1", "1");
- table.put("n2", "2");
- table.put("n3", "3");
+ table.setObject("n1", "1");
+ table.setObject("n2", "2");
+ table.setObject("n3", "3");
+
+
+ Assert.assertEquals("1", table.getObject("n1"));
+ Assert.assertEquals("2", table.getObject("n2"));
+ Assert.assertEquals("3", table.getObject("n3"));
- Iterator iterator = table.keySet().iterator();
- Assert.assertEquals("n1", iterator.next());
- Assert.assertEquals("n2", iterator.next());
- Assert.assertEquals("n3", iterator.next());
- Assert.assertFalse(iterator.hasNext());
diff --git a/java/common/src/test/java/org/apache/qpid/pool/PoolingFilterTest.java b/java/common/src/test/java/org/apache/qpid/pool/PoolingFilterTest.java
index 972a935257..6383d52298 100644
--- a/java/common/src/test/java/org/apache/qpid/pool/PoolingFilterTest.java
+++ b/java/common/src/test/java/org/apache/qpid/pool/PoolingFilterTest.java
@@ -36,25 +36,32 @@ public class PoolingFilterTest extends TestCase
public void setUp()
{
+
//Create Pool
_executorService = ReferenceCountingExecutorService.getInstance();
_executorService.acquireExecutorService();
- _pool = new PoolingFilter(_executorService, PoolingFilter.WRITE_EVENTS,
+ _pool = PoolingFilter.createAynschWritePoolingFilter(_executorService,
"AsynchronousWriteFilter");
}
public void testRejectedExecution() throws Exception
{
- _pool.filterWrite(new NoOpFilter(), new TestSession(), new IoFilter.WriteRequest("Message"));
+
+ TestSession testSession = new TestSession();
+ _pool.createNewJobForSession(testSession);
+ _pool.filterWrite(new NoOpFilter(), testSession, new IoFilter.WriteRequest("Message"));
//Shutdown the pool
_executorService.getPool().shutdownNow();
try
{
+
+ testSession = new TestSession();
+ _pool.createNewJobForSession(testSession);
//prior to fix for QPID-172 this would throw RejectedExecutionException
- _pool.filterWrite(null, new TestSession(), null);
+ _pool.filterWrite(null, testSession, null);
}
catch (RejectedExecutionException rje)
{
diff --git a/java/common/src/test/java/org/apache/qpid/session/TestSession.java b/java/common/src/test/java/org/apache/qpid/session/TestSession.java
index f10d55e9d0..aafc91b03b 100644
--- a/java/common/src/test/java/org/apache/qpid/session/TestSession.java
+++ b/java/common/src/test/java/org/apache/qpid/session/TestSession.java
@@ -24,9 +24,13 @@ import org.apache.mina.common.*;
import java.net.SocketAddress;
import java.util.Set;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.ConcurrentHashMap;
public class TestSession implements IoSession
{
+ private final ConcurrentMap attributes = new ConcurrentHashMap();
+
public TestSession()
{
}
@@ -68,42 +72,42 @@ public class TestSession implements IoSession
public Object getAttachment()
{
- return null; //TODO
+ return getAttribute("");
}
public Object setAttachment(Object attachment)
{
- return null; //TODO
+ return setAttribute("",attachment);
}
public Object getAttribute(String key)
{
- return null; //TODO
+ return attributes.get(key);
}
public Object setAttribute(String key, Object value)
{
- return null; //TODO
+ return attributes.put(key,value);
}
public Object setAttribute(String key)
{
- return null; //TODO
+ return attributes.put(key, Boolean.TRUE);
}
public Object removeAttribute(String key)
{
- return null; //TODO
+ return attributes.remove(key);
}
public boolean containsAttribute(String key)
{
- return false; //TODO
+ return attributes.containsKey(key);
}
public Set getAttributeKeys()
{
- return null; //TODO
+ return attributes.keySet();
}
public TransportType getTransportType()
diff --git a/java/distribution/pom.xml b/java/distribution/pom.xml
index ca91c222ee..366b478687 100644
--- a/java/distribution/pom.xml
+++ b/java/distribution/pom.xml
@@ -16,7 +16,10 @@
specific language governing permissions and limitations
under the License.
-->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
<modelVersion>4.0.0</modelVersion>
<groupId>org.apache.qpid</groupId>
<artifactId>qpid-distribution</artifactId>
@@ -36,7 +39,7 @@
<qpid.version>${pom.version}</qpid.version>
<qpid.targetDir>${project.build.directory}</qpid.targetDir>
</properties>
-
+
<repositories>
<repository>
<id>repo1.maven.org</id>
@@ -48,18 +51,15 @@
<dependencies>
<dependency>
<groupId>${pom.groupId}</groupId>
- <artifactId>qpid-common</artifactId>
- <version>${pom.version}</version>
- </dependency>
- <dependency>
- <groupId>${pom.groupId}</groupId>
<artifactId>qpid-broker</artifactId>
<version>${pom.version}</version>
+ <type>jar</type>
</dependency>
<dependency>
<groupId>${pom.groupId}</groupId>
<artifactId>qpid-client</artifactId>
<version>${pom.version}</version>
+ <type>jar</type>
</dependency>
<dependency>
<groupId>${pom.groupId}.management</groupId>
@@ -85,7 +85,7 @@
<version>${assembly.version}</version>
<configuration>
<descriptors>
- <descriptor>src/main/assembly/bin.xml</descriptor>
+ <descriptor>src/main/assembly/bin.xml</descriptor>
</descriptors>
<finalName>qpid-${pom.version}</finalName>
<outputDirectory>${qpid.targetDir}</outputDirectory>
@@ -106,14 +106,7 @@
</plugin>
</plugins>
</pluginManagement>
- <resources>
- <resource>
- <directory>src/main/java</directory>
- <includes>
- <include>**/*</include>
- </includes>
- </resource>
- </resources>
+
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
@@ -127,7 +120,6 @@
<configuration>
<descriptors>
<descriptor>src/main/assembly/bin.xml</descriptor>
- <descriptor>src/main/assembly/client-bin.xml</descriptor>
<descriptor>src/main/assembly/src.xml</descriptor>
<descriptor>src/main/assembly/management-eclipse-plugin.xml</descriptor>
<descriptor>src/main/assembly/management-eclipse-plugin-unix.xml</descriptor>
@@ -139,4 +131,74 @@
</plugin>
</plugins>
</build>
-</project>
+
+ <profiles>
+ <profile>
+ <id>tests</id>
+
+ <dependencies>
+ <dependency>
+ <groupId>${pom.groupId}</groupId>
+ <artifactId>qpid-broker</artifactId>
+ <version>${pom.version}</version>
+ <type>jar</type>
+ </dependency>
+ <dependency>
+ <groupId>${pom.groupId}</groupId>
+ <artifactId>qpid-broker</artifactId>
+ <version>${pom.version}</version>
+ <type>test-jar</type>
+ </dependency>
+ <dependency>
+ <groupId>${pom.groupId}</groupId>
+ <artifactId>qpid-client</artifactId>
+ <version>${pom.version}</version>
+ <type>jar</type>
+ </dependency>
+ <dependency>
+ <groupId>${pom.groupId}</groupId>
+ <artifactId>qpid-client</artifactId>
+ <version>${pom.version}</version>
+ <type>test-jar</type>
+ </dependency>
+ <dependency>
+ <groupId>${pom.groupId}</groupId>
+ <artifactId>qpid-perftests</artifactId>
+ <version>${pom.version}</version>
+ <type>test-jar</type>
+ </dependency>
+ <dependency>
+ <groupId>${pom.groupId}</groupId>
+ <artifactId>qpid-systests</artifactId>
+ <version>${pom.version}</version>
+ <type>test-jar</type>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <artifactId>maven-assembly-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>distribution-package</id>
+ <phase>package</phase>
+ <goals>
+ <goal>single</goal>
+ </goals>
+ <configuration>
+ <descriptors>
+ <descriptor>src/main/assembly/bin-test.xml</descriptor>
+ </descriptors>
+ <finalName>qpid-${pom.version}</finalName>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+
+ </profile>
+ </profiles>
+
+</project>
diff --git a/java/distribution/src/main/assembly/bin-test.xml b/java/distribution/src/main/assembly/bin-test.xml
new file mode 100644
index 0000000000..b7896bd697
--- /dev/null
+++ b/java/distribution/src/main/assembly/bin-test.xml
@@ -0,0 +1,169 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ * 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.
+-->
+<assembly>
+ <!-- id typically identifies the "type" (src vs bin etc) of the assembly -->
+ <id>java-bin-with-tests</id>
+ <includeBaseDirectory>false</includeBaseDirectory>
+ <formats>
+ <format>tar.gz</format>
+ <format>zip</format>
+ </formats>
+
+ <fileSets>
+ <fileSet>
+ <directory>src/main/release</directory>
+ <outputDirectory>qpid-${qpid.version}</outputDirectory>
+ <includes>
+ <include>DISCLAIMER</include>
+ <include>LICENSE.txt</include>
+ <include>NOTICE.txt</include>
+ <include>README.txt</include>
+ </includes>
+ </fileSet>
+ <fileSet>
+ <directory>..</directory>
+ <outputDirectory>qpid-${qpid.version}</outputDirectory>
+ <includes>
+ <include>*.txt</include>
+ </includes>
+ </fileSet>
+ <fileSet>
+ <directory>src/main/release/etc</directory>
+ <outputDirectory>qpid-${qpid.version}/etc</outputDirectory>
+ <includes>
+ <include>logging.properties</include>
+ <include>log4j.properties</include>
+ </includes>
+ </fileSet>
+ <fileSet>
+ <directory>src/main/release/docs</directory>
+ <outputDirectory>qpid-${qpid.version}/docs</outputDirectory>
+ <includes>
+ <include>RELEASE_NOTES.txt</include>
+ </includes>
+ </fileSet>
+ <fileSet>
+ <directory>target</directory>
+ <outputDirectory>qpid-${qpid.version}/lib</outputDirectory>
+ <includes>
+ <include>qpid-incubating.jar</include>
+ </includes>
+ </fileSet>
+ </fileSets>
+ <files>
+ <!-- due to a bug in the assembly plugin (MASSEMBLY-153) you have
+ to use decimal numbers to specify fileMode -->
+ <file>
+ <source>../common/etc/qpid-run.conf</source>
+ <outputDirectory>qpid-${qpid.version}/etc</outputDirectory>
+ <destName>qpid-run.conf</destName>
+ </file>
+ <file>
+ <source>../broker/etc/config.xml</source>
+ <outputDirectory>qpid-${qpid.version}/etc</outputDirectory>
+ <destName>config.xml</destName>
+ </file>
+ <file>
+ <source>../broker/etc/log4j.xml</source>
+ <outputDirectory>qpid-${qpid.version}/etc</outputDirectory>
+ <destName>log4j.xml</destName>
+ </file>
+ <file>
+ <source>../broker/etc/passwd</source>
+ <outputDirectory>qpid-${qpid.version}/etc</outputDirectory>
+ <destName>passwd</destName>
+ </file>
+ <file>
+ <source>../broker/etc/qpid-server.conf</source>
+ <outputDirectory>qpid-${qpid.version}/etc</outputDirectory>
+ <destName>qpid-server.conf</destName>
+ </file>
+ <file>
+ <source>../broker/etc/virtualhosts.xml</source>
+ <outputDirectory>qpid-${qpid.version}/etc</outputDirectory>
+ <destName>virtualhosts.xml</destName>
+ </file>
+ <file>
+ <source>../common/bin/qpid-run</source>
+ <outputDirectory>qpid-${qpid.version}/bin</outputDirectory>
+ <destName>qpid-run</destName>
+ <fileMode>0755</fileMode>
+ </file>
+ <file>
+ <source>../broker/bin/qpid-server</source>
+ <outputDirectory>qpid-${qpid.version}/bin</outputDirectory>
+ <destName>qpid-server</destName>
+ <fileMode>0755</fileMode>
+ </file>
+ <file>
+ <source>../broker/bin/qpid-server.bat</source>
+ <outputDirectory>qpid-${qpid.version}/bin</outputDirectory>
+ <destName>qpid-server.bat</destName>
+ <fileMode>0755</fileMode>
+ </file>
+ <file>
+ <source>../broker/bin/run.bat</source>
+ <outputDirectory>qpid-${qpid.version}/bin</outputDirectory>
+ <destName>run.bat</destName>
+ <fileMode>0755</fileMode>
+ </file>
+ <file>
+ <source>../broker/bin/run.sh</source>
+ <outputDirectory>qpid-${qpid.version}/bin</outputDirectory>
+ <destName>run.sh</destName>
+ <fileMode>0755</fileMode>
+ </file>
+ <file>
+ <source>../broker/bin/runAll</source>
+ <outputDirectory>qpid-${qpid.version}/bin</outputDirectory>
+ <destName>runAll</destName>
+ <fileMode>0755</fileMode>
+ </file>
+ </files>
+ <dependencySets>
+ <dependencySet>
+ <outputDirectory>qpid-${qpid.version}/lib</outputDirectory>
+ <unpack>false</unpack>
+ <excludes>
+ <exclude>org.apache.qpid:qpid-distribution</exclude>
+ <exclude>org.apache.qpid.management:org.apache.qpid.management.ui</exclude>
+ <exclude>org.eclipse.core:org.eclipse.core.commands</exclude>
+ <exclude>org.eclipse.core:org.eclipse.core.contenttype</exclude>
+ <exclude>org.eclipse.core:org.eclipse.core.expressions</exclude>
+ <exclude>org.eclipse.core:org.eclipse.core.jobs</exclude>
+ <exclude>org.eclipse.core:org.eclipse.core.runtime</exclude>
+ <exclude>org.eclipse.core:org.eclipse.core.runtime.compatibility.auth</exclude>
+ <exclude>org.eclipse.core:org.eclipse.core.runtime.compatibility.registry</exclude>
+ <exclude>org.eclipse.equinox:org.eclipse.equinox.common</exclude>
+ <exclude>org.eclipse.equinox:org.eclipse.equinox.preferences</exclude>
+ <exclude>org.eclipse.equinox:org.eclipse.equinox.registry</exclude>
+ <exclude>org.eclipse.help:org.eclipse.help</exclude>
+ <exclude>org.eclipse.jface:org.eclipse.jface</exclude>
+ <exclude>org.eclipse.osgi:org.eclipse.osgi</exclude>
+ <exclude>org.eclipse.swt:org.eclipse.swt</exclude>
+ <exclude>org.eclipse.swt:org.eclipse.swt.win32.win32.x86</exclude>
+ <exclude>org.eclipse.ui:org.eclipse.ui</exclude>
+ <exclude>org.eclipse.ui:org.eclipse.ui.forms</exclude>
+ <exclude>org.eclipse.ui:org.eclipse.ui.workbench</exclude>
+ </excludes>
+ <scope>runtime</scope>
+ </dependencySet>
+ </dependencySets>
+</assembly>
diff --git a/java/distribution/src/main/assembly/bin.xml b/java/distribution/src/main/assembly/bin.xml
index 9b0a56a744..978ee4df82 100644
--- a/java/distribution/src/main/assembly/bin.xml
+++ b/java/distribution/src/main/assembly/bin.xml
@@ -31,14 +31,17 @@
<directory>src/main/release</directory>
<outputDirectory>qpid-${qpid.version}</outputDirectory>
<includes>
- <include>DISCLAIMER</include>
+ <include>DISCLAIMER</include>
+ <include>LICENSE.txt</include>
+ <include>NOTICE.txt</include>
+ <include>README.txt</include>
</includes>
</fileSet>
<fileSet>
<directory>..</directory>
<outputDirectory>qpid-${qpid.version}</outputDirectory>
<includes>
- <include>*.txt</include>
+ <include>*.txt</include>
</includes>
</fileSet>
<fileSet>
@@ -53,14 +56,14 @@
<directory>src/main/release/docs</directory>
<outputDirectory>qpid-${qpid.version}/docs</outputDirectory>
<includes>
- <include>RELEASE_NOTES.txt</include>
+ <include>RELEASE_NOTES.txt</include>
</includes>
</fileSet>
<fileSet>
<directory>target</directory>
<outputDirectory>qpid-${qpid.version}/lib</outputDirectory>
<includes>
- <include>qpid-incubating.jar</include>
+ <include>qpid-incubating.jar</include>
</includes>
</fileSet>
</fileSets>
@@ -71,73 +74,67 @@
<source>../common/etc/qpid-run.conf</source>
<outputDirectory>qpid-${qpid.version}/etc</outputDirectory>
<destName>qpid-run.conf</destName>
- <fileMode>420</fileMode>
</file>
<file>
<source>../broker/etc/config.xml</source>
<outputDirectory>qpid-${qpid.version}/etc</outputDirectory>
<destName>config.xml</destName>
- <fileMode>420</fileMode>
</file>
<file>
<source>../broker/etc/log4j.xml</source>
<outputDirectory>qpid-${qpid.version}/etc</outputDirectory>
<destName>log4j.xml</destName>
- <fileMode>420</fileMode>
</file>
<file>
<source>../broker/etc/passwd</source>
<outputDirectory>qpid-${qpid.version}/etc</outputDirectory>
<destName>passwd</destName>
- <fileMode>420</fileMode>
</file>
<file>
<source>../broker/etc/qpid-server.conf</source>
<outputDirectory>qpid-${qpid.version}/etc</outputDirectory>
<destName>qpid-server.conf</destName>
- <fileMode>420</fileMode>
</file>
<file>
<source>../broker/etc/virtualhosts.xml</source>
<outputDirectory>qpid-${qpid.version}/etc</outputDirectory>
<destName>virtualhosts.xml</destName>
- <fileMode>420</fileMode>
</file>
<file>
<source>../common/bin/qpid-run</source>
<outputDirectory>qpid-${qpid.version}/bin</outputDirectory>
<destName>qpid-run</destName>
- <fileMode>493</fileMode>
+ <fileMode>0755</fileMode>
</file>
<file>
<source>../broker/bin/qpid-server</source>
<outputDirectory>qpid-${qpid.version}/bin</outputDirectory>
<destName>qpid-server</destName>
- <fileMode>493</fileMode>
+ <fileMode>0755</fileMode>
</file>
<file>
<source>../broker/bin/qpid-server.bat</source>
<outputDirectory>qpid-${qpid.version}/bin</outputDirectory>
<destName>qpid-server.bat</destName>
- <fileMode>493</fileMode>
+ <fileMode>0755</fileMode>
</file>
<file>
<source>../broker/bin/run.bat</source>
<outputDirectory>qpid-${qpid.version}/bin</outputDirectory>
<destName>run.bat</destName>
- <fileMode>493</fileMode>
+ <fileMode>0755</fileMode>
</file>
<file>
<source>../broker/bin/run.sh</source>
<outputDirectory>qpid-${qpid.version}/bin</outputDirectory>
<destName>run.sh</destName>
- <fileMode>493</fileMode>
+ <fileMode>0755</fileMode>
</file>
<file>
<source>../broker/bin/runAll</source>
<outputDirectory>qpid-${qpid.version}/bin</outputDirectory>
<destName>runAll</destName>
- <fileMode>493</fileMode>
+ <fileMode>0755</fileMode>
</file>
</files>
<dependencySets>
diff --git a/java/distribution/src/main/assembly/management-eclipse-plugin-unix.xml b/java/distribution/src/main/assembly/management-eclipse-plugin-unix.xml
index 5ac131b12b..1318248b2a 100644
--- a/java/distribution/src/main/assembly/management-eclipse-plugin-unix.xml
+++ b/java/distribution/src/main/assembly/management-eclipse-plugin-unix.xml
@@ -19,11 +19,10 @@
-->
<assembly>
<!-- id typically identifies the "type" (src vs bin etc) of the assembly -->
- <id>eclipse-plugin-unix</id>
+ <id>management-console-unix</id>
<includeBaseDirectory>false</includeBaseDirectory>
<formats>
<format>tar.gz</format>
- <format>zip</format>
</formats>
<!--
<moduleSets>
@@ -75,10 +74,17 @@
</includes>
</fileSet>
<fileSet>
+ <directory>../management/eclipse-plugin</directory>
+ <outputDirectory>qpidmc</outputDirectory>
+ <includes>
+ <include>README.txt</include>
+ </includes>
+ </fileSet>
+ <fileSet>
<directory>../management/eclipse-plugin/bin</directory>
<outputDirectory>qpidmc/bin</outputDirectory>
<includes>
- <include>qpidmc.sh</include>
+ <include>qpidmc*.sh</include>
</includes>
<fileMode>777</fileMode>
</fileSet>
diff --git a/java/distribution/src/main/assembly/management-eclipse-plugin.xml b/java/distribution/src/main/assembly/management-eclipse-plugin.xml
index f6c2399785..5d89c55968 100644
--- a/java/distribution/src/main/assembly/management-eclipse-plugin.xml
+++ b/java/distribution/src/main/assembly/management-eclipse-plugin.xml
@@ -74,6 +74,13 @@
</includes>
</fileSet>
<fileSet>
+ <directory>../management/eclipse-plugin</directory>
+ <outputDirectory>qpidmc</outputDirectory>
+ <includes>
+ <include>README.txt</include>
+ </includes>
+ </fileSet>
+ <fileSet>
<directory>../management/eclipse-plugin/bin</directory>
<outputDirectory>qpidmc/bin</outputDirectory>
<includes>
diff --git a/java/distribution/src/main/assembly/src.xml b/java/distribution/src/main/assembly/src.xml
index b66425c3d2..49e1f8bfb2 100644
--- a/java/distribution/src/main/assembly/src.xml
+++ b/java/distribution/src/main/assembly/src.xml
@@ -32,10 +32,10 @@
<outputDirectory>qpid-${qpid.version}-src</outputDirectory>
<includes>
<include>DISCLAIMER</include>
- <include>LICENSE</include>
+ <include>LICENSE.txt</include>
<include>licenses/*.*</include>
- <include>NOTICE</include>
- <include>README</include>
+ <include>NOTICE.txt</include>
+ <include>README.txt</include>
<include>BUILDING.txt</include>
</includes>
</fileSet>
diff --git a/java/LICENSE.txt b/java/distribution/src/main/release/LICENSE.txt
index 6b0b1270ff..6b0b1270ff 100755
--- a/java/LICENSE.txt
+++ b/java/distribution/src/main/release/LICENSE.txt
diff --git a/java/NOTICE.txt b/java/distribution/src/main/release/NOTICE.txt
index 82d3dbc632..82d3dbc632 100644
--- a/java/NOTICE.txt
+++ b/java/distribution/src/main/release/NOTICE.txt
diff --git a/java/README.txt b/java/distribution/src/main/release/README.txt
index 14706170bc..14706170bc 100644
--- a/java/README.txt
+++ b/java/distribution/src/main/release/README.txt
diff --git a/java/etc/log4j.xml b/java/etc/log4j.xml
new file mode 100644
index 0000000000..d314d8fb23
--- /dev/null
+++ b/java/etc/log4j.xml
@@ -0,0 +1,43 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
+
+<!-- ===================================================================== -->
+<!-- -->
+<!-- Log4j Configuration -->
+<!-- -->
+<!-- ===================================================================== -->
+
+<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
+
+ <!-- ============================== -->
+ <!-- Append messages to the console -->
+ <!-- ============================== -->
+
+ <appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
+ <param name="Target" value="System.out"/>
+ <param name="Threshold" value="ALL"/>
+
+ <layout class="org.apache.log4j.PatternLayout">
+ <!-- The default pattern: Date Priority [Category] Message\n -->
+ <param name="ConversionPattern" value="%m%n"/>
+ </layout>
+
+ </appender>
+
+ <!-- ================ -->
+ <!-- Limit categories -->
+ <!-- ================ -->
+
+ <category name="org.apache.qpid">
+ <priority value="${amqj.logging.level}" logger="CONSOLE"/>
+ </category>
+
+ <!-- ======================= -->
+ <!-- Setup the Root category -->
+ <!-- ======================= -->
+
+ <root level="${root.logging.level}">
+ <appender-ref ref="CONSOLE"/>
+ </root>
+
+</log4j:configuration>
diff --git a/java/management/eclipse-plugin/README.txt b/java/management/eclipse-plugin/README.txt
index 2cbfbc623c..5325bf27ec 100644
--- a/java/management/eclipse-plugin/README.txt
+++ b/java/management/eclipse-plugin/README.txt
@@ -4,4 +4,18 @@ Running the Qpid Management Console (eclipse-plugin)
To run the management console, set the QPIDMC_HOME environment variable to
qpid management console root directory (e.g. C:/qpidmc)and add $QPIDMC_HOME/bin to your PATH.
-Then run the qpidmc.bat batch file to launch the management console.
+Then run the script to launch the management console-
+For Windows:
+------------
+qpidmc.bat
+qpidmc.sh (using cygwin)
+
+Unix:
+-----
+qpidmc.sh <operating system> <windowing system> <platform achitecture>
+eg. qpidms.sh linux motif x86
+qpidmc_motif.sh
+qpidmc_gtk.sh
+
+Apache confluence page for latest information:
+http://cwiki.apache.org/confluence/display/qpid/Qpid+Management+Console
diff --git a/java/management/eclipse-plugin/bin/qpidmc.sh b/java/management/eclipse-plugin/bin/qpidmc.sh
index c9ab423fdd..e5e67c6d90 100755
--- a/java/management/eclipse-plugin/bin/qpidmc.sh
+++ b/java/management/eclipse-plugin/bin/qpidmc.sh
@@ -1,3 +1,54 @@
#!/bin/bash
+#
+# 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.
+#
-"$JAVA_HOME/bin/java" -Xms40m -Xmx256m -Declipse.consoleLog=false -jar $QPIDMC_HOME/eclipse/startup.jar org.eclipse.core.launcher.Main -launcher $QPIDMC_HOME/eclipse/eclipse -name "Qpid Management Console" -showsplash 600 -configuration "file:$QPIDMC_HOME/configuration"
+if [ "$JAVA_HOME" == "" ]; then
+ echo "The JAVA_HOME environment variable is not defined";
+ exit 0;
+fi
+
+if [ "$QPIDMC_HOME" == "" ]; then
+ echo "The QPIDMC_HOME environment variable is not defined correctly";
+ exit 0;
+fi
+
+os=win32
+ws=win32
+arch=x86
+
+##echo $os
+##echo $ws
+##echo $arch
+
+## If this is to be run on different platform other than windows then following parameters should be passed
+## qpidmc.sh <operating system> <windowing system> <platform achitecture>
+## eg. qpidmc.sh linux motif x86
+if [ $# -eq 3 ]; then
+ os=$1
+ ws=$2
+ arch=$3
+fi
+
+if [ $os = "SunOS" ]; then
+ os="solaris"
+elif [ $os = "Linux" ]; then
+ os="linux"
+fi
+
+"$JAVA_HOME/bin/java" -Xms40m -Xmx256m -Declipse.consoleLog=false -jar $QPIDMC_HOME/eclipse/startup.jar org.eclipse.core.launcher.Main -launcher $QPIDMC_HOME/eclipse/eclipse -name "Qpid Management Console" -showsplash 600 -configuration "file:$QPIDMC_HOME/configuration" -os $os -ws $ws -arch $arch
diff --git a/java/perftests/bin/topicPublisher.sh b/java/management/eclipse-plugin/bin/qpidmc_gtk.sh
index cc3a8736cc..7b42b9525e 100755
--- a/java/perftests/bin/topicPublisher.sh
+++ b/java/management/eclipse-plugin/bin/qpidmc_gtk.sh
@@ -18,6 +18,7 @@
# under the License.
#
-# XXX -Xmx512m -Xms512m -XX:NewSize=150m
-. ./setupclasspath.sh
-$JAVA_HOME/bin/java -cp $CP -Damqj.logging.level="INFO" org.apache.qpid.topic.Publisher $*
+os=`uname`
+arch=`uname -p`
+
+$QPIDMC_HOME/bin/qpidmc.sh $os gtk $arch
diff --git a/java/perftests/bin/topicListener.sh b/java/management/eclipse-plugin/bin/qpidmc_motif.sh
index 454efefe7d..49354f12f6 100755
--- a/java/perftests/bin/topicListener.sh
+++ b/java/management/eclipse-plugin/bin/qpidmc_motif.sh
@@ -18,8 +18,7 @@
# under the License.
#
+os=`uname`
+arch=`uname -p`
-# XXX -Xmx512m -Xms512m -XX:NewSize=150m
-. ./setupclasspath.sh
-echo $CP
-$JAVA_HOME/bin/java -cp $CP -Damqj.logging.level="INFO" org.apache.qpid.topic.Listener $*
+$QPIDMC_HOME/bin/qpidmc.sh $os motif $arch
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/Constants.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/Constants.java
index 756d404596..2fadee6f54 100644
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/Constants.java
+++ b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/Constants.java
@@ -32,12 +32,15 @@ public class Constants
public final static String ITEM_TYPE = "type";
public final static String SERVER = "server";
public final static String DOMAIN = "domain";
- public final static String TYPE = "mbeantype";
+ public final static String NODE_TYPE_MBEANTYPE = "mbeantype";
+ // currently used only for virtual host instances, but will work as general also
+ public final static String TYPE_INSTANCE = "mbeantype_instance";
public final static String MBEAN = "mbean";
public final static String ATTRIBUTE = "Attribute";
public final static String ATTRIBUTES = "Attributes";
public final static String NOTIFICATION = "Notifications";
public final static String RESULT = "Result";
+ public final static String VIRTUAL_HOST = "VirtualHost";
public final static String ATTRIBUTE_QUEUE_DEPTH = "QueueDepth";
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ManagedBean.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ManagedBean.java
index 7da5621345..e87d77159d 100644
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ManagedBean.java
+++ b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ManagedBean.java
@@ -32,6 +32,7 @@ public abstract class ManagedBean extends ManagedObject
private String _uniqueName = "";
private String _domain = "";
private String _type = "";
+ private String _virtualHostName = "Default";
private ManagedServer _server = null;
private HashMap _properties = null;
@@ -47,6 +48,7 @@ public abstract class ManagedBean extends ManagedObject
public void setProperties(HashMap properties)
{
this._properties = properties;
+ setVirtualHostName(getProperty(Constants.VIRTUAL_HOST));
}
public String getDomain()
{
@@ -82,4 +84,17 @@ public abstract class ManagedBean extends ManagedObject
this._uniqueName = uniqueName;
}
+ public String getVirtualHostName()
+ {
+ return _virtualHostName;
+ }
+
+ public void setVirtualHostName(String virtualHost)
+ {
+ if (virtualHost != null)
+ {
+ this._virtualHostName = virtualHost;
+ }
+ }
+
}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ServerRegistry.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ServerRegistry.java
index 6fbfdcd06f..4f6bbd8bc0 100644
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ServerRegistry.java
+++ b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/ServerRegistry.java
@@ -23,6 +23,8 @@ package org.apache.qpid.management.ui;
import java.util.ArrayList;
import java.util.List;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
import org.apache.qpid.management.ui.jmx.ClientListener;
import org.apache.qpid.management.ui.model.ManagedAttributeModel;
@@ -33,11 +35,14 @@ public abstract class ServerRegistry
{
private ManagedServer _managedServer = null;
// list of all Connection mbeans
- protected List<ManagedBean> _connections = new ArrayList<ManagedBean>();
+ //private List<ManagedBean> _connections = new ArrayList<ManagedBean>();
+ private ConcurrentMap<String,List<ManagedBean>> _connections = new ConcurrentHashMap<String,List<ManagedBean>>();
// list of all exchange mbeans
- protected List<ManagedBean> _exchanges = new ArrayList<ManagedBean>();
+ //private List<ManagedBean> _exchanges = new ArrayList<ManagedBean>();
+ private ConcurrentMap<String,List<ManagedBean>> _exchanges = new ConcurrentHashMap<String,List<ManagedBean>>();
// list of all queue mbenas
- protected List<ManagedBean> _queues = new ArrayList<ManagedBean>();
+ //private List<ManagedBean> _queues = new ArrayList<ManagedBean>();
+ private ConcurrentMap<String,List<ManagedBean>> _queues = new ConcurrentHashMap<String,List<ManagedBean>>();
public ServerRegistry()
{
@@ -61,47 +66,58 @@ public abstract class ServerRegistry
protected void addConnectionMBean(ManagedBean mbean)
{
- _connections.add(mbean);
+ String vHost = mbean.getVirtualHostName();
+ _connections.putIfAbsent(vHost, new ArrayList<ManagedBean>());
+ List<ManagedBean> beans = _connections.get(vHost);
+ beans.add(mbean);
}
protected void addExchangeMBean(ManagedBean mbean)
{
- _exchanges.add(mbean);
+ String vHost = mbean.getVirtualHostName();
+ _exchanges.putIfAbsent(vHost, new ArrayList<ManagedBean>());
+ List<ManagedBean> beans = _exchanges.get(vHost);
+ beans.add(mbean);
}
protected void addQueueMBean(ManagedBean mbean)
{
- _queues.add(mbean);
+ String vHost = mbean.getVirtualHostName();
+ _queues.putIfAbsent(vHost, new ArrayList<ManagedBean>());
+ List<ManagedBean> beans = _queues.get(vHost);
+ beans.add(mbean);
}
protected void removeConnectionMBean(ManagedBean mbean)
{
- _connections.remove(mbean);
+ String vHost = mbean.getVirtualHostName();
+ List<ManagedBean> beans = _connections.get(vHost);
+ beans.remove(mbean);
}
protected void removeExchangeMBean(ManagedBean mbean)
{
- _exchanges.remove(mbean);
+ _exchanges.get(mbean.getVirtualHostName()).remove(mbean);
}
protected void removeQueueMBean(ManagedBean mbean)
{
- _queues.remove(mbean);
+ _queues.get(mbean.getVirtualHostName()).remove(mbean);
}
- public List<ManagedBean> getConnections()
+ public List<ManagedBean> getConnections(String virtualHost)
{
- return _connections;
+ return _connections.get(virtualHost);
}
- public List<ManagedBean> getExchanges()
+ public List<ManagedBean> getExchanges(String virtualHost)
{
- return _exchanges;
+ return _exchanges.get(virtualHost);
}
- public List<ManagedBean> getQueues()
+ public List<ManagedBean> getQueues(String virtualHost)
{
- return _queues;
+ return _queues.get(virtualHost);
}
public abstract void addManagedObject(ManagedBean key);
@@ -123,11 +139,11 @@ public abstract class ServerRegistry
public abstract OperationDataModel getOperationModel(ManagedBean mbean);
- public abstract String[] getQueueNames();
+ public abstract String[] getQueueNames(String vistualHostName);
- public abstract String[] getExchangeNames();
+ public abstract String[] getExchangeNames(String vistualHostName);
- public abstract String[] getConnectionNames();
+ public abstract String[] getConnectionNames(String vistualHostName);
public abstract List<NotificationObject> getNotifications(ManagedBean mbean);
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/ClientListener.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/ClientListener.java
index 00a9ae7653..6a23051a9e 100644
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/ClientListener.java
+++ b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/ClientListener.java
@@ -43,8 +43,6 @@ public class ClientListener implements NotificationListener
public void handleNotification(Notification notification, Object handback)
{
- System.out.println("\nReceived server notification: " + notification);
-
ObjectName objName = null;
String type = notification.getType();
if (MBeanServerNotification.REGISTRATION_NOTIFICATION.equals(type))
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/ClientNotificationListener.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/ClientNotificationListener.java
index 31b761fcf3..c6ecda4b4c 100644
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/ClientNotificationListener.java
+++ b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/ClientNotificationListener.java
@@ -34,7 +34,6 @@ public class ClientNotificationListener extends ClientListener
public void handleNotification(Notification notification, Object handback)
{
- System.out.println("\nReceived mbean notification: " + notification);
ObjectName objName = (ObjectName)notification.getSource();
//String type = notification.getType();
getServerRegistry().addNotification(objName, notification);
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/JMXServerRegistry.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/JMXServerRegistry.java
index c087bd2e72..72c4fa3d9d 100644
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/JMXServerRegistry.java
+++ b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/jmx/JMXServerRegistry.java
@@ -131,15 +131,15 @@ public class JMXServerRegistry extends ServerRegistry
public void addManagedObject(ManagedBean mbean)
{
- if (Constants.QUEUE.equals(mbean.getType()) && !mbean.getName().startsWith("tmp_"))
+ if (mbean.getType().endsWith(Constants.QUEUE) && !mbean.getName().startsWith("tmp_"))
{
addQueueMBean(mbean);
}
- else if (Constants.EXCHANGE.equals(mbean.getType()))
+ else if (mbean.getType().endsWith(Constants.EXCHANGE))
{
addExchangeMBean(mbean);
}
- else if (Constants.CONNECTION.equals(mbean.getType()))
+ else if (mbean.getType().endsWith(Constants.CONNECTION))
{
addConnectionMBean(mbean);
}
@@ -149,11 +149,11 @@ public class JMXServerRegistry extends ServerRegistry
public void removeManagedObject(ManagedBean mbean)
{
- if (Constants.QUEUE.equals(mbean.getType()))
+ if (mbean.getType().endsWith(Constants.QUEUE))
removeQueueMBean(mbean);
- else if (Constants.EXCHANGE.equals(mbean.getType()))
+ else if (mbean.getType().endsWith(Constants.EXCHANGE))
removeExchangeMBean(mbean);
- else if (Constants.CONNECTION.equals(mbean.getType()))
+ else if (mbean.getType().endsWith(Constants.CONNECTION))
removeConnectionMBean(mbean);
_mbeansMap.remove(mbean.getUniqueName());
@@ -212,21 +212,31 @@ public class JMXServerRegistry extends ServerRegistry
_notificationsMap.get(mbean.getUniqueName()).clear();
}
+ /**
+ * Adds notification name and type to the map. The map contains all the notification names,
+ * subscribed for an mbean.
+ * @param mbean
+ * @param name
+ * @param type
+ */
public void addNotificationListener(ManagedBean mbean, String name, String type)
{
- HashMap<String, List<String>> map = _subscribedNotificationMap.get(mbean.getUniqueName());
+ // Get the subscribed notifications map for given mbean. If map is null then create a new one.
+ HashMap<String, List<String>> map = _subscribedNotificationMap.get(mbean.getUniqueName());
if (map == null)
{
map = new HashMap<String, List<String>>();
_subscribedNotificationMap.put(mbean.getUniqueName(),map);
}
+ // Get the list of notification types for given notification name. If null, then create a new list.
List<String> list = map.get(name);
if (list == null)
{
list = new ArrayList<String>();
map.put(name, list);
}
+ // Now add the notification type to the list
if (Constants.ALL.equals(type))
{
List<NotificationInfoModel> infoList = _notificationInfoMap.get(mbean.getUniqueName());
@@ -247,9 +257,12 @@ public class JMXServerRegistry extends ServerRegistry
list.add(type);
}
- System.out.println("Subscribed for notification :" + mbean.getUniqueName());
+ //System.out.println("Subscribed for notification :" + mbean.getUniqueName());
}
+ /**
+ * Checks if the given notification name and type are subscribed for the mbean.
+ */
public boolean hasSubscribedForNotifications(ManagedBean mbean, String name, String type)
{
if (_subscribedNotificationMap.containsKey(mbean.getUniqueName()))
@@ -266,11 +279,20 @@ public class JMXServerRegistry extends ServerRegistry
return false;
}
+ /**
+ * Clears the notification name and type information from the subscribed notifications map
+ * and removes the listener from mbeanserver connection
+ * @param mbean
+ * @param name
+ * @param type
+ * @throws Exception
+ */
public void removeNotificationListener(ManagedBean mbean, String name, String type) throws Exception
{
- System.out.println("Removed notification listener :" + mbean.getUniqueName() + name +type);
+ //System.out.println("Removed notification listener :" + mbean.getUniqueName() + name +type);
if (_subscribedNotificationMap.containsKey(mbean.getUniqueName()))
{
+ // get the notifications map. This map contains the notification name mapped with the notification types
HashMap<String, List<String>> map = _subscribedNotificationMap.get(mbean.getUniqueName());
if (map.containsKey(name))
{
@@ -281,8 +303,16 @@ public class JMXServerRegistry extends ServerRegistry
else if (type != null)
{
map.get(name).remove(type);
+ if (map.get(name).isEmpty())
+ {
+ map.remove(name);
+ }
}
}
+ if (map.size() == 0)
+ {
+ _subscribedNotificationMap.remove(mbean.getUniqueName());
+ }
JMXManagedObject jmxbean = (JMXManagedObject)mbean;
_mbsc.removeNotificationListener(jmxbean.getObjectName(), _notificationListener);
@@ -335,33 +365,45 @@ public class JMXServerRegistry extends ServerRegistry
return _operationModelMap.get(mbean.getUniqueName());
}
- public String[] getQueueNames()
+ public String[] getQueueNames(String virtualHostName)
{
- String[] queues = new String[_queues.size()];
+ List<ManagedBean> list = getQueues(virtualHostName);
+ if (list == null)
+ return null;
+
+ String[] queues = new String[list.size()];
int i = 0;
- for (ManagedBean mbean : _queues)
+ for (ManagedBean mbean : list)
{
queues[i++] = mbean.getName();
}
return queues;
}
- public String[] getExchangeNames()
+ public String[] getExchangeNames(String virtualHostName)
{
- String[] exchanges = new String[_exchanges.size()];
+ List<ManagedBean> list = getExchanges(virtualHostName);
+ if (list == null)
+ return null;
+
+ String[] exchanges = new String[list.size()];
int i = 0;
- for (ManagedBean mbean : _exchanges)
+ for (ManagedBean mbean : list)
{
exchanges[i++] = mbean.getName();
}
return exchanges;
}
- public String[] getConnectionNames()
+ public String[] getConnectionNames(String virtualHostName)
{
- String[] connections = new String[_connections.size()];
+ List<ManagedBean> list = getExchanges(virtualHostName);
+ if (list == null)
+ return null;
+
+ String[] connections = new String[list.size()];
int i = 0;
- for (ManagedBean mbean : _connections)
+ for (ManagedBean mbean : list)
{
connections[i++] = mbean.getName();
}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/AttributeData.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/AttributeData.java
index 601f499a0c..ccd4cf8df8 100644
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/AttributeData.java
+++ b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/model/AttributeData.java
@@ -25,7 +25,7 @@ public class AttributeData
String name = "";
String description = "";
String dataType = "";
- Object value = null;
+ Object value = "";
boolean readable = true;
boolean writable = false;
@@ -63,7 +63,8 @@ public class AttributeData
}
public void setValue(Object value)
{
- this.value = value;
+ if (value != null)
+ this.value = value;
}
public boolean isReadable()
{
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/AttributesTabControl.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/AttributesTabControl.java
index 8bf4e30c64..2b8e5cee1a 100644
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/AttributesTabControl.java
+++ b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/AttributesTabControl.java
@@ -20,8 +20,6 @@
*/
package org.apache.qpid.management.ui.views;
-import javax.management.openmbean.TabularDataSupport;
-
import org.apache.qpid.management.ui.ApplicationRegistry;
import org.apache.qpid.management.ui.Constants;
import org.apache.qpid.management.ui.ManagedBean;
@@ -421,7 +419,7 @@ public class AttributesTabControl extends TabControl
{
int width = 500;
int height = 250;
- if (data.getValue() instanceof TabularDataSupport)
+ if (!isSimpleType(data.getValue()))
{
width = 650;
height = 450;
@@ -516,12 +514,12 @@ public class AttributesTabControl extends TabControl
}
else
{
- if (attribute.getValue() instanceof TabularDataSupport)
+ if (!isSimpleType(attribute.getValue()))
{
Composite composite = new Composite(parent, SWT.BORDER);
composite.setLayout(new GridLayout());
composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
- ViewUtility.createTabularDataHolder(_toolkit, composite,(TabularDataSupport)attribute.getValue());
+ ViewUtility.populateCompositeWithData(_toolkit, composite, attribute.getValue());
}
else
{
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/MBeanTypeTabControl.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/MBeanTypeTabControl.java
index 73d56634ec..3e76e3e1c0 100644
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/MBeanTypeTabControl.java
+++ b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/MBeanTypeTabControl.java
@@ -233,19 +233,19 @@ public class MBeanTypeTabControl
// populate the map and list with appropriate mbeans
if (_type.equals(Constants.QUEUE))
{
- list = serverRegistry.getQueues();
+ list = serverRegistry.getQueues(MBeanView.getVirtualHost());
items = getQueueItems(list);
_sortBySizeButton.setVisible(true);
}
else if (_type.equals(Constants.EXCHANGE))
{
- list = serverRegistry.getExchanges();
+ list = serverRegistry.getExchanges(MBeanView.getVirtualHost());
items = getItems(list);
_sortBySizeButton.setVisible(false);
}
else if (_type.equals(Constants.CONNECTION))
{
- list = serverRegistry.getConnections();
+ list = serverRegistry.getConnections(MBeanView.getVirtualHost());
items = getItems(list);
_sortBySizeButton.setVisible(false);
}
@@ -255,11 +255,15 @@ public class MBeanTypeTabControl
}
_list.setItems(items);
+
}
// sets the map with appropriate mbean and name
private String[] getItems(java.util.List<ManagedBean> list)
{
+ if (list == null)
+ return new String[0];
+
Collections.sort(list, _sorterByName);
String[] items = new String[list.size()];
int i = 0;
@@ -273,6 +277,9 @@ public class MBeanTypeTabControl
private String[] getQueueItems(java.util.List<ManagedBean> list) throws Exception
{
+ if (list == null)
+ return new String[0];
+
// Sort the list. It will keep the mbeans in sorted order in the _queueMap, which is required for
// sorting the queue according to size etc
Collections.sort(list, _sorterByName);
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/MBeanView.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/MBeanView.java
index 96981e755f..e3cd92f38a 100644
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/MBeanView.java
+++ b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/MBeanView.java
@@ -64,6 +64,7 @@ public class MBeanView extends ViewPart
private static ManagedServer _server = null;
private TreeObject _selectedNode = null;
private ManagedBean _mbean = null;
+ private static String _virtualHostName = null;
// This map contains a TabFolder for each kind of MBean. TabFolder is mapped with mbeantype(eg Connection, Queue etc)
private HashMap<String, TabFolder> tabFolderMap = new HashMap<String, TabFolder>();
private ISelectionListener selectionListener = new SelectionListenerImpl();
@@ -102,14 +103,10 @@ public class MBeanView extends ViewPart
setServer();
try
{
- if (Constants.TYPE.equals(_selectedNode.getType()))
+ if (Constants.NODE_TYPE_MBEANTYPE.equals(_selectedNode.getType()))
{
refreshTypeTabFolder(_selectedNode.getName());
}
- else if (Constants.DOMAIN.equals(_selectedNode.getType()))
- {
- refreshTypeTabFolder(typeTabFolder.getItem(0));
- }
else
{
showSelectedMBean();
@@ -134,16 +131,20 @@ public class MBeanView extends ViewPart
if (Constants.SERVER.equals(_selectedNode.getType()))
{
_server = (ManagedServer)_selectedNode.getManagedObject();
+ _virtualHostName = null;
}
else
{
TreeObject parent = _selectedNode.getParent();
- while (!parent.getType().equals(Constants.SERVER))
+ while (parent != null && !parent.getType().equals(Constants.SERVER))
{
parent = parent.getParent();
}
- _server = (ManagedServer)parent.getManagedObject();
+ if (parent != null && parent.getType().equals(Constants.SERVER))
+ _server = (ManagedServer)parent.getManagedObject();
+
+ _virtualHostName = _selectedNode.getVirtualHost();
}
}
@@ -152,6 +153,11 @@ public class MBeanView extends ViewPart
return _server;
}
+ public static String getVirtualHost()
+ {
+ return _virtualHostName;
+ }
+
private void showSelectedMBean() throws Exception
{
if (Constants.NOTIFICATION.equals(_selectedNode.getType()))
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/NavigationView.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/NavigationView.java
index 619aa06598..8e262075a9 100644
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/NavigationView.java
+++ b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/NavigationView.java
@@ -33,6 +33,7 @@ import java.util.List;
import org.apache.qpid.management.ui.ApplicationRegistry;
import org.apache.qpid.management.ui.Constants;
import org.apache.qpid.management.ui.ManagedBean;
+import org.apache.qpid.management.ui.ManagedObject;
import org.apache.qpid.management.ui.ManagedServer;
import org.apache.qpid.management.ui.ServerRegistry;
import org.apache.qpid.management.ui.exceptions.InfoRequiredException;
@@ -266,7 +267,7 @@ public class NavigationView extends ViewPart
catch(Exception ex)
{
System.out.println("\nError in connecting to Qpid broker ");
- System.out.println("\n" + ex.toString());
+ ex.printStackTrace();
}
}
@@ -280,7 +281,7 @@ public class NavigationView extends ViewPart
private void populateDomain(TreeObject domain) throws IOException, Exception
{
ManagedServer server = (ManagedServer)domain.getParent().getManagedObject();
-
+ /*
// Add these three types - Connection, Exchange, Queue
// By adding these, these will always be available, even if there are no mbeans under thse types
// This is required because, the mbeans will be added from mbeanview, by selecting from the list
@@ -290,7 +291,7 @@ public class NavigationView extends ViewPart
typeChild.setParent(domain);
typeChild = new TreeObject(Constants.QUEUE, Constants.TYPE);
typeChild.setParent(domain);
-
+ */
// Now populate the mbenas under those types
List<ManagedBean> mbeans = MBeanUtility.getManagedObjectsForDomain(server, domain.getName());
@@ -302,27 +303,43 @@ public class NavigationView extends ViewPart
// Add all mbeans other than Connections, Exchanges and Queues. Because these will be added
// manually by selecting from MBeanView
- if (!(mbean.getType().equals(Constants.CONNECTION) || mbean.getType().equals(Constants.EXCHANGE) || mbean.getType().equals(Constants.QUEUE)))
+
+ if (!(mbean.getType().endsWith(Constants.CONNECTION) ||
+ mbean.getType().endsWith(Constants.EXCHANGE) ||
+ mbean.getType().endsWith(Constants.QUEUE)))
{
addManagedBean(domain, mbean);
}
}
}
+ private void addDefaultNodes(TreeObject parent)
+ {
+ TreeObject typeChild = new TreeObject(Constants.CONNECTION, Constants.NODE_TYPE_MBEANTYPE);
+ typeChild.setParent(parent);
+ typeChild.setVirtualHost(parent.getVirtualHost());
+ typeChild = new TreeObject(Constants.EXCHANGE, Constants.NODE_TYPE_MBEANTYPE);
+ typeChild.setParent(parent);
+ typeChild.setVirtualHost(parent.getVirtualHost());
+ typeChild = new TreeObject(Constants.QUEUE, Constants.NODE_TYPE_MBEANTYPE);
+ typeChild.setParent(parent);
+ typeChild.setVirtualHost(parent.getVirtualHost());
+ }
+
/**
* Checks if a particular mbeantype is already there in the navigation view for a domain.
* This is used while populating domain with mbeans.
- * @param domain
+ * @param parent
* @param typeName
* @return Node if given mbeantype already exists, otherwise null
*/
- private TreeObject getMBeanTypeNode(TreeObject domain, String typeName)
+ private TreeObject getMBeanTypeNode(TreeObject parent, String typeName)
{
- List<TreeObject> childNodes = domain.getChildren();
-
+ List<TreeObject> childNodes = parent.getChildren();
for (TreeObject child : childNodes)
{
- if (Constants.TYPE.equals(child.getType()) && typeName.equals(child.getName()))
+ if ((Constants.NODE_TYPE_MBEANTYPE.equals(child.getType()) || Constants.TYPE_INSTANCE.equals(child.getType())) &&
+ typeName.equals(child.getName()))
return child;
}
return null;
@@ -346,46 +363,82 @@ public class NavigationView extends ViewPart
*/
private void addManagedBean(TreeObject domain, ManagedBean mbean) throws Exception
{
- String type = mbean.getType();
String name = mbean.getName();
-
- TreeObject typeNode = getMBeanTypeNode(domain, type);
- if (typeNode != null && doesMBeanNodeAlreadyExist(typeNode, name))
- return;
-
- TreeObject mbeanNode = null;
- if (typeNode != null) // type node already exists
- {
- if (name == null)
+ String[] types = mbean.getType().split("\\.");
+ TreeObject typeNode = null;
+ TreeObject parentNode = domain;
+ // Run this loop till all nodes for this mbean are created.
+ for (int i = 0; i < types.length; i++)
+ {
+ String type = types[i];
+ String valueOftype = mbean.getProperty(type);
+ typeNode = getMBeanTypeNode(parentNode, type);
+
+ if (typeNode == null)
{
- throw new ManagementConsoleException("Two mbeans can't exist without a name and with same type");
+ // If the ObjectName doesn't have name property, that means there will be only one instance
+ // of this mbean for given "type". So there will be no type node created for this mbean.
+ if (name == null && (i == types.length -1))
+ {
+ break;
+ }
+ typeNode = createTypeNode(parentNode, type);
+ typeNode.setVirtualHost(mbean.getVirtualHostName());
}
- mbeanNode = new TreeObject(mbean);
- mbeanNode.setParent(typeNode);
- }
- else
- {
- // type node does not exist. Now check if node to be created as mbeantype or MBean
- if (name != null) // A managedObject with type and name
+ parentNode = typeNode;
+
+ // Create instances node for this type if value exists. For eg, for different virtual hosts, the
+ // nodes with given value will be created.
+ if (valueOftype == null)
{
- typeNode = new TreeObject(type, Constants.TYPE);
- typeNode.setParent(domain);
- mbeanNode = new TreeObject(mbean);
- mbeanNode.setParent(typeNode);
- }
- else // A managedObject with only type
+ break;
+ }
+ typeNode = getMBeanTypeNode(parentNode, valueOftype);
+ if (typeNode == null)
{
- mbeanNode = new TreeObject(mbean);
- mbeanNode.setParent(domain);
+ typeNode = createTypeInstanceNode(parentNode, valueOftype);
+ typeNode.setVirtualHost(mbean.getVirtualHostName());
+
+ // Create default nodes for VHost instances
+ if (type.equals(Constants.VIRTUAL_HOST))
+ {
+ addDefaultNodes(typeNode);
+ }
}
+ parentNode = typeNode;
+ }
+
+ if (typeNode == null)
+ {
+ typeNode = parentNode;
}
+ if (doesMBeanNodeAlreadyExist(typeNode, name))
+ return;
+
+ TreeObject mbeanNode = new TreeObject(mbean);
+ mbeanNode.setParent(typeNode);
+
// Add notification node
// TODO: show this only if the mbean sends any notification
TreeObject notificationNode = new TreeObject(Constants.NOTIFICATION, Constants.NOTIFICATION);
notificationNode.setParent(mbeanNode);
}
+ private TreeObject createTypeNode(TreeObject parent, String name)
+ {
+ TreeObject typeNode = new TreeObject(name, Constants.NODE_TYPE_MBEANTYPE);
+ typeNode.setParent(parent);
+ return typeNode;
+ }
+
+ private TreeObject createTypeInstanceNode(TreeObject parent, String name)
+ {
+ TreeObject typeNode = new TreeObject(name, Constants.TYPE_INSTANCE);
+ typeNode.setParent(parent);
+ return typeNode;
+ }
+
/**
* Removes all the child nodes of the given parent node
* @param parent
@@ -678,7 +731,14 @@ public class NavigationView extends ViewPart
public String getText(Object element)
{
TreeObject node = (TreeObject)element;
- return node.getName();
+ if (node.getType().equals(Constants.NODE_TYPE_MBEANTYPE))
+ {
+ return node.getName() + "s";
+ }
+ else
+ {
+ return node.getName();
+ }
}
public Font getFont(Object element)
@@ -718,19 +778,21 @@ public class NavigationView extends ViewPart
{
while(true)
{
- if (_managedServerMap.isEmpty())
- continue;
+ if (!_managedServerMap.isEmpty())
+ {
+ refreshRemovedObjects();
+ refreshClosedServerConnections();
+ }
try
{
- Thread.sleep(2000);
+ Thread.sleep(3000);
}
catch(Exception ex)
{
}
- refreshRemovedObjects();
- refreshClosedServerConnections();
+
}// end of while loop
}// end of run method.
}// end of Worker class
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/NotificationsTabControl.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/NotificationsTabControl.java
index 3eb93f55d3..c45ad7b362 100644
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/NotificationsTabControl.java
+++ b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/NotificationsTabControl.java
@@ -326,7 +326,6 @@ public class NotificationsTabControl extends TabControl
Shell shell = null;
public void doubleClick(DoubleClickEvent event)
{
- System.out.println("DoubleClickEvent" + event);
display = Display.getCurrent();
shell = new Shell(display, SWT.BORDER | SWT.CLOSE | SWT.MIN |
SWT.MAX | SWT.RESIZE);
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/OperationTabControl.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/OperationTabControl.java
index 58349ab7a5..8568ee33bf 100644
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/OperationTabControl.java
+++ b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/OperationTabControl.java
@@ -24,9 +24,6 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
-import javax.management.openmbean.CompositeDataSupport;
-import javax.management.openmbean.TabularDataSupport;
-
import org.apache.qpid.management.ui.ApplicationRegistry;
import org.apache.qpid.management.ui.Constants;
import org.apache.qpid.management.ui.ManagedBean;
@@ -92,6 +89,7 @@ public class OperationTabControl extends TabControl
// for customized method in header exchange
private HashMap<Text, Text> headerBindingHashMap = null;
+ private String _virtualHostName = null;
public OperationTabControl(TabFolder tabFolder)
{
@@ -155,6 +153,7 @@ public class OperationTabControl extends TabControl
{
_mbean = mbean;
_opData = opData;
+ _virtualHostName = _mbean.getProperty(Constants.VIRTUAL_HOST);
// Setting the form to be invisible. Just in case the mbean server connection
// is done and it takes time in getting the response, then the ui should be blank
@@ -219,8 +218,8 @@ public class OperationTabControl extends TabControl
}
// Customised parameter widgets
- if (_mbean.getType().equals(Constants.EXCHANGE) &&
- "headers".equals(_mbean.getProperty(Constants.EXCHANGE_TYPE)) &&
+ if (_mbean.getType().endsWith(Constants.EXCHANGE) &&
+ Constants.EXCHANGE_TYPE_VALUES[2].equals(_mbean.getProperty(Constants.EXCHANGE_TYPE)) &&
_opData.getName().equalsIgnoreCase("createNewBinding"))
{
customCreateNewBinding();
@@ -247,7 +246,7 @@ public class OperationTabControl extends TabControl
if (param.getName().equals(Constants.QUEUE))
{
Combo combo = new Combo(_paramsComposite, SWT.READ_ONLY | SWT.DROP_DOWN);
- String[] items = ApplicationRegistry.getServerRegistry(_mbean).getQueueNames();
+ String[] items = ApplicationRegistry.getServerRegistry(_mbean).getQueueNames(_virtualHostName);
combo.setItems(items);
combo.add("Select Queue", 0);
combo.select(0);
@@ -259,7 +258,7 @@ public class OperationTabControl extends TabControl
else if (param.getName().equals(Constants.EXCHANGE))
{
Combo combo = new Combo(_paramsComposite, SWT.READ_ONLY | SWT.DROP_DOWN);
- String[] items = ApplicationRegistry.getServerRegistry(_mbean).getExchangeNames();
+ String[] items = ApplicationRegistry.getServerRegistry(_mbean).getExchangeNames(_virtualHostName);
combo.setItems(items);
combo.add("Select Exchange", 0);
combo.select(0);
@@ -360,8 +359,8 @@ public class OperationTabControl extends TabControl
formData.left = new FormAttachment(label, 5);
formData.right = new FormAttachment(valueNumerator);
- Combo combo = new Combo(composite, SWT.READ_ONLY | SWT.DROP_DOWN);
- String[] items = ApplicationRegistry.getServerRegistry(_mbean).getQueueNames();
+ Combo combo = new Combo(composite, SWT.READ_ONLY | SWT.DROP_DOWN);
+ String[] items = ApplicationRegistry.getServerRegistry(_mbean).getQueueNames(_virtualHostName);
combo.setItems(items);
combo.add("Select Queue", 0);
combo.select(0);
@@ -472,7 +471,7 @@ public class OperationTabControl extends TabControl
int width = 600;
int height = 400;
Shell shell = ViewUtility.createPopupShell(Constants.RESULT, width, height);
- populateResults(result, shell);
+ ViewUtility.populateCompositeWithData(_toolkit, shell, result);
shell.open();
while (!shell.isDisposed()) {
@@ -484,23 +483,6 @@ public class OperationTabControl extends TabControl
}
/**
- * Displays the operation result
- * @param result
- * @param parent
- */
- private void populateResults(Object result, Composite parent)
- {
- if (result instanceof TabularDataSupport)
- {
- ViewUtility.createTabularDataHolder(_toolkit, parent, (TabularDataSupport)result);
- }
- else if (result instanceof CompositeDataSupport)
- {
- ViewUtility.populateCompositeDataHolder(_toolkit, parent, (CompositeDataSupport)result);
- }
- }
-
- /**
* Clears the parameter values of the operation
*/
private void clearParameters()
@@ -521,7 +503,7 @@ public class OperationTabControl extends TabControl
*/
private void clearParameterValues(Composite control)
{
- if (control == null)
+ if (control == null || (control.isDisposed()))
return;
Control[] controls = control.getChildren();
@@ -623,7 +605,7 @@ public class OperationTabControl extends TabControl
else
{
ViewUtility.disposeChildren(_resultsComposite);
- populateResults(result, _resultsComposite);
+ ViewUtility.populateCompositeWithData(_toolkit, _resultsComposite, result);
_resultsComposite.layout();
_form.layout();
}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/TabControl.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/TabControl.java
index c8916044cb..0793e33538 100644
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/TabControl.java
+++ b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/TabControl.java
@@ -20,6 +20,8 @@
*/
package org.apache.qpid.management.ui.views;
+import java.util.ArrayList;
+
import org.apache.qpid.management.ui.ManagedBean;
import org.apache.qpid.management.ui.model.OperationData;
import org.eclipse.swt.widgets.Control;
@@ -34,6 +36,26 @@ public abstract class TabControl
protected ManagedBean _mbean = null;
protected TabFolder _tabFolder = null;
+ private static java.util.List<String> simpleTypes = new ArrayList<String>();
+
+ static
+ {
+ simpleTypes.add("java.math.BigDecimal");
+ simpleTypes.add("java.math.BigInteger");
+ simpleTypes.add("java.lang.Boolean");
+ simpleTypes.add("java.lang.Byte");
+ simpleTypes.add("java.lang.Character");
+ simpleTypes.add("java.util.Date");
+ simpleTypes.add("java.lang.Double");
+ simpleTypes.add("java.lang.Float");
+ simpleTypes.add("java.lang.Integer");
+ simpleTypes.add("java.lang.Long");
+ simpleTypes.add("javax.management.ObjectName");
+ simpleTypes.add("java.lang.Short");
+ simpleTypes.add("java.lang.String");
+ simpleTypes.add("boolean");
+ }
+
public TabControl(TabFolder tabFolder)
{
_tabFolder = tabFolder;
@@ -61,4 +83,9 @@ public abstract class TabControl
{
}
+
+ public boolean isSimpleType(Object data)
+ {
+ return simpleTypes.contains(data.getClass().getName());
+ }
}
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/TreeObject.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/TreeObject.java
index 36dc753a1e..29d6b2edc4 100644
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/TreeObject.java
+++ b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/TreeObject.java
@@ -32,6 +32,7 @@ public class TreeObject
private String _name;
private String _type;
private String _url;
+ private String _virtualHost;
private TreeObject _parent;
private List<TreeObject> _children = new ArrayList<TreeObject>();
private ManagedObject _object;
@@ -47,7 +48,8 @@ public class TreeObject
_name = obj.getName();
if (_name == null && (obj instanceof ManagedBean))
{
- _name = ((ManagedBean)obj).getType();
+ String[] types = ((ManagedBean)obj).getType().split("\\.");
+ _name = types[types.length - 1];
}
this._type = Constants.MBEAN;
this._object = obj;
@@ -96,6 +98,16 @@ public class TreeObject
{
this._url = url;
}
+
+ public String getVirtualHost()
+ {
+ return _virtualHost;
+ }
+
+ public void setVirtualHost(String vHost)
+ {
+ _virtualHost = vHost;
+ }
public ManagedObject getManagedObject()
{
diff --git a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/ViewUtility.java b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/ViewUtility.java
index ef3d6f0106..c21be5d68c 100644
--- a/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/ViewUtility.java
+++ b/java/management/eclipse-plugin/src/main/java/org/apache/qpid/management/ui/views/ViewUtility.java
@@ -28,6 +28,7 @@ import java.util.Set;
import javax.management.openmbean.ArrayType;
import javax.management.openmbean.CompositeData;
+import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.CompositeType;
import javax.management.openmbean.OpenType;
import javax.management.openmbean.TabularDataSupport;
@@ -53,6 +54,10 @@ import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.widgets.FormToolkit;
+/**
+ * Utility Class for displaying OpenMbean data types by creating required SWT widgets
+ * @author Bhupendra Bhardwaj
+ */
public class ViewUtility
{
public static final String OP_NAME = "operation_name";
@@ -77,8 +82,26 @@ public class ViewUtility
SUPPORTED_ARRAY_DATATYPES.add("java.util.Date");
}
+ /**
+ * Populates the composite with given openmbean data type (TabularType or CompositeType)
+ * @param toolkit
+ * @param parent composite
+ * @param data open mbean data type(either composite type or tabular data type)
+ */
+ public static void populateCompositeWithData(FormToolkit toolkit, Composite parent, Object data)
+ {
+ if (data instanceof TabularDataSupport)
+ {
+ ViewUtility.createTabularDataHolder(toolkit, parent, (TabularDataSupport)data);
+ }
+ else if (data instanceof CompositeDataSupport)
+ {
+ ViewUtility.populateCompositeWithCompositeData(toolkit, parent, (CompositeDataSupport)data);
+ }
+ }
+
@SuppressWarnings("unchecked")
- public static void createTabularDataHolder(FormToolkit toolkit, Composite parent, TabularDataSupport tabularData)
+ private static void createTabularDataHolder(FormToolkit toolkit, Composite parent, TabularDataSupport tabularData)
{
Composite composite = toolkit.createComposite(parent, SWT.BORDER);
GridLayout layout = new GridLayout(4, true);
@@ -109,7 +132,7 @@ public class ViewUtility
// display the first record
CompositeData data = (CompositeData)(list.get(0)).getValue();
composite.setData(INDEX, 0);
- populateCompositeDataHolder(toolkit, compositeDataHolder, data);
+ populateCompositeWithCompositeData(toolkit, compositeDataHolder, data);
enableOrDisableTraversalButtons(composite);
}
@@ -135,7 +158,15 @@ public class ViewUtility
}
}
- public static Composite createCompositeDataHolder(final FormToolkit toolkit, final Composite dataHolder, CompositeType compositeType)
+ /**
+ * Sets up the given composite for holding a CompositeData. Create traversal buttons, label etc and
+ * creates a child Composite, which should be populated with the CompositeData
+ * @param toolkit
+ * @param dataHolder
+ * @param compositeType
+ * @return
+ */
+ private static Composite createCompositeDataHolder(final FormToolkit toolkit, final Composite dataHolder, CompositeType compositeType)
{
String desc = compositeType.getDescription();
Label description = toolkit.createLabel(dataHolder, desc, SWT.CENTER);
@@ -164,6 +195,7 @@ public class ViewUtility
layoutData.widthHint = 80;
lastRecordButton.setLayoutData(layoutData);
+ // Now create the composite, which will hold the CompositeData
final Composite composite = toolkit.createComposite(dataHolder, SWT.NONE);
GridLayout layout = new GridLayout();
layout.horizontalSpacing = layout.verticalSpacing = 0;
@@ -179,7 +211,8 @@ public class ViewUtility
dataHolder.setData(PREV, previousRecordButton);
dataHolder.setData(LAST, lastRecordButton);
- // Listener for the traversal buttons
+ // Listener for the traversal buttons. When a button is clicked the respective
+ // CompositeData will be populated in the composite
SelectionListener listener = new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
@@ -188,8 +221,9 @@ public class ViewUtility
return;
Button traverseButton =(Button)e.widget;
+ // Get the CompositeData respective to the button selected
CompositeData data = getCompositeData(dataHolder, traverseButton.getText());
- populateCompositeDataHolder(toolkit, composite, data);
+ populateCompositeWithCompositeData(toolkit, composite, data);
enableOrDisableTraversalButtons(dataHolder);
}
};
@@ -202,6 +236,13 @@ public class ViewUtility
return composite;
}
+ /**
+ * The CompositeData is set as data with the Composite and using the index, this method will
+ * return the corresponding CompositeData
+ * @param compositeHolder
+ * @param dataIndex
+ * @return the CompositeData respective to the index
+ */
private static CompositeData getCompositeData(Composite compositeHolder, String dataIndex)
{
List objectData = (List)compositeHolder.getData();
@@ -236,13 +277,18 @@ public class ViewUtility
// Set the index being shown.
compositeHolder.setData(INDEX, index);
- System.out.println("index :" + index);
return (CompositeData)((Map.Entry)objectData.get(index)).getValue();
}
+ /**
+ * Populates the given composite with the CompositeData. Creates required widgets to hold the data types
+ * @param toolkit
+ * @param parent
+ * @param data CompositeData
+ */
@SuppressWarnings("unchecked")
- public static void populateCompositeDataHolder(FormToolkit toolkit, Composite parent, CompositeData data/*String dataIndex*/)
+ private static void populateCompositeWithCompositeData(FormToolkit toolkit, Composite parent, CompositeData data)
{
Control[] oldControls = parent.getChildren();
for (int i = 0; i < oldControls.length; i++)
@@ -273,7 +319,6 @@ public class ViewUtility
if (itemType.isArray())
{
OpenType type = ((ArrayType)itemType).getElementOpenType();
- System.out.println("Array Element type = " + type.getClassName());
// If Byte array and mimetype is text, convert to text string
if (type.getClassName().equals(Byte.class.getName()))
{
@@ -343,7 +388,6 @@ public class ViewUtility
try
{
String textMessage = new String(byteArray, encoding);
- System.out.println("\nMessage : \n" + textMessage + "\n");
Text valueText = toolkit.createText(compositeHolder, textMessage, SWT.READ_ONLY | SWT.BORDER |
SWT.MULTI | SWT.WRAP | SWT.V_SCROLL);
diff --git a/java/management/eclipse-plugin/src/main/resources/unix/configuration/config.ini b/java/management/eclipse-plugin/src/main/resources/unix/configuration/config.ini
index d50b06cbcf..aa2d21fd48 100644
--- a/java/management/eclipse-plugin/src/main/resources/unix/configuration/config.ini
+++ b/java/management/eclipse-plugin/src/main/resources/unix/configuration/config.ini
@@ -24,3 +24,4 @@ eclipse.product=org.apache.qpid.management.ui.product
eclipse.application=org.apache.qpid.management.ui.application
osgi.bundles=org.eclipse.equinox.common@2:start,org.eclipse.core.runtime@start,com.ibm.icu,org.apache.qpid.management.ui,org.eclipse.core.commands,org.eclipse.core.contenttype,org.eclipse.core.expressions,org.eclipse.core.jobs,org.eclipse.core.runtime.compatibility.auth,org.eclipse.core.runtime.compatibility.registry,org.eclipse.equinox.preferences,org.eclipse.equinox.registry,org.eclipse.help,org.eclipse.jface,org.eclipse.swt,org.eclipse.swt.motif.linux.x86,org.eclipse.swt.gtk.linux.x86_64,org.eclipse.swt.gtk.linux.x86,org.eclipse.swt.gtk.linux.ppc,org.eclipse.swt.motif.hpux.PA_RISC,org.eclipse.swt.gtk.solaris.sparc,org.eclipse.swt.motif.solaris.sparc,org.eclipse.swt.carbon.macocx,org.eclipse.ui,org.eclipse.ui.forms,org.eclipse.ui.workbench
osgi.bundles.defaultStartLevel=4
+eof=eof \ No newline at end of file
diff --git a/java/mvn-repo/README.txt b/java/mvn-repo/README.txt
new file mode 100644
index 0000000000..c78cda6938
--- /dev/null
+++ b/java/mvn-repo/README.txt
@@ -0,0 +1,5 @@
+Temporary local repository for jars that are not available in the central repository yet.
+This was created because junit-toolkit is undergoing some development to use it with perf tests. Its an Apache licensed performance testing utility.
+It takes 2-4 days to get something added to the central repo but want to keep up with changed to junit-toolkit. This repository holds a snapshot
+of it, so that the build can get it from somewhere without breaking. It is anticipated that it will reach a stable 0.5 version within two weeks from
+30/01/2007, at which time it will be placed in the central repo and this local repository will be deleted.
diff --git a/java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/0.5-SNAPSHOT/junit-toolkit-maven-plugin-0.5-20070130.111904-1.jar b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/0.5-SNAPSHOT/junit-toolkit-maven-plugin-0.5-20070130.111904-1.jar
new file mode 100644
index 0000000000..43c678f547
--- /dev/null
+++ b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/0.5-SNAPSHOT/junit-toolkit-maven-plugin-0.5-20070130.111904-1.jar
Binary files differ
diff --git a/java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/0.5-SNAPSHOT/junit-toolkit-maven-plugin-0.5-20070130.111904-1.jar.md5 b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/0.5-SNAPSHOT/junit-toolkit-maven-plugin-0.5-20070130.111904-1.jar.md5
new file mode 100644
index 0000000000..87820b3b0a
--- /dev/null
+++ b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/0.5-SNAPSHOT/junit-toolkit-maven-plugin-0.5-20070130.111904-1.jar.md5
@@ -0,0 +1 @@
+8aff63861edb0a6bb47b5fad955a6ba5 \ No newline at end of file
diff --git a/java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/0.5-SNAPSHOT/junit-toolkit-maven-plugin-0.5-20070130.111904-1.jar.sha1 b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/0.5-SNAPSHOT/junit-toolkit-maven-plugin-0.5-20070130.111904-1.jar.sha1
new file mode 100644
index 0000000000..5a72a41b79
--- /dev/null
+++ b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/0.5-SNAPSHOT/junit-toolkit-maven-plugin-0.5-20070130.111904-1.jar.sha1
@@ -0,0 +1 @@
+600209771b236268f1b939e4a924899875ee8562 \ No newline at end of file
diff --git a/java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/0.5-SNAPSHOT/junit-toolkit-maven-plugin-0.5-20070130.111904-1.pom b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/0.5-SNAPSHOT/junit-toolkit-maven-plugin-0.5-20070130.111904-1.pom
new file mode 100644
index 0000000000..65587eb683
--- /dev/null
+++ b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/0.5-SNAPSHOT/junit-toolkit-maven-plugin-0.5-20070130.111904-1.pom
@@ -0,0 +1,91 @@
+<?xml version="1.0" encoding="UTF-8"?><project>
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>uk.co.thebadgerset</groupId>
+ <artifactId>junit-toolkit-maven-plugin</artifactId>
+ <packaging>maven-plugin</packaging>
+ <name>junit-toolkit-maven-plugin</name>
+ <version>0.5-20070130.111904-1</version>
+ <description>Maven plugin for the JUnit Toolkit to run performance tests with TKTestRunner.</description>
+ <url>http://www.thebadgerset.co.uk/projects/junit-toolkit-maven-plugin</url>
+ <licenses>
+ <license>
+ <name>The Apache Software License, Version 2.0</name>
+ <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
+ <distribution>repo</distribution>
+ </license>
+ </licenses>
+ <scm>
+ <connection>scm:${scm.setup}/junit-toolkit-maven-plugin</connection>
+ </scm>
+ <organization>
+ <name>The Badger Set trading as Liberty Bishop (1151) ltd.</name>
+ <url>http://www.thebadgerset.co.uk/</url>
+ </organization>
+ <build>
+ <sourceDirectory>src/main</sourceDirectory>
+ <pluginManagement>
+ <plugins>
+ <plugin>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <version>2.0.1</version>
+ <configuration>
+ <source>1.5</source>
+ <target>1.5</target>
+ <fork>false</fork>
+ </configuration>
+ </plugin>
+ </plugins>
+ </pluginManagement>
+ </build>
+ <dependencies>
+ <dependency>
+ <groupId>uk.co.thebadgerset</groupId>
+ <artifactId>junit-toolkit</artifactId>
+ <version>0.5-SNAPSHOT</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.maven</groupId>
+ <artifactId>maven-plugin-api</artifactId>
+ <version>2.0.4</version>
+ </dependency>
+ </dependencies>
+ <reporting>
+ <plugins>
+ <plugin>
+ <artifactId>maven-pmd-plugin</artifactId>
+ <configuration>
+ <linkXref>true</linkXref>
+ <sourceEncoding>utf-8</sourceEncoding>
+ <minimumTokens>20</minimumTokens>
+ <targetJdk>1.5</targetJdk>
+ </configuration>
+ </plugin>
+ <plugin>
+ <artifactId>maven-jxr-plugin</artifactId>
+ </plugin>
+ <plugin>
+ <artifactId>maven-javadoc-plugin</artifactId>
+ </plugin>
+ <plugin>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <configuration>
+ <configLocation>../mavenbuild/coding_standards.xml</configLocation>
+ </configuration>
+ </plugin>
+ </plugins>
+ </reporting>
+ <distributionManagement>
+ <repository>
+ <uniqueVersion>false</uniqueVersion>
+ <id>release-repo</id>
+ <name>The Badger Set Maven2 Repository</name>
+ <url>file://c:/temp</url>
+ </repository>
+ <snapshotRepository>
+ <id>snapshot-repo</id>
+ <name>The Badger Set Maven2 Snapshot Repository</name>
+ <url>file://c:/temp</url>
+ </snapshotRepository>
+ <status>deployed</status>
+ </distributionManagement>
+</project> \ No newline at end of file
diff --git a/java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/0.5-SNAPSHOT/junit-toolkit-maven-plugin-0.5-20070130.111904-1.pom.md5 b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/0.5-SNAPSHOT/junit-toolkit-maven-plugin-0.5-20070130.111904-1.pom.md5
new file mode 100644
index 0000000000..adf20d93ad
--- /dev/null
+++ b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/0.5-SNAPSHOT/junit-toolkit-maven-plugin-0.5-20070130.111904-1.pom.md5
@@ -0,0 +1 @@
+4ab65f208ffa4400551233321b90933a \ No newline at end of file
diff --git a/java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/0.5-SNAPSHOT/junit-toolkit-maven-plugin-0.5-20070130.111904-1.pom.sha1 b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/0.5-SNAPSHOT/junit-toolkit-maven-plugin-0.5-20070130.111904-1.pom.sha1
new file mode 100644
index 0000000000..aeb3966048
--- /dev/null
+++ b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/0.5-SNAPSHOT/junit-toolkit-maven-plugin-0.5-20070130.111904-1.pom.sha1
@@ -0,0 +1 @@
+84f491024bd60142781ef9035f4394cb1379902d \ No newline at end of file
diff --git a/java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/0.5-SNAPSHOT/maven-metadata.xml b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/0.5-SNAPSHOT/maven-metadata.xml
new file mode 100644
index 0000000000..0a46c1d79a
--- /dev/null
+++ b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/0.5-SNAPSHOT/maven-metadata.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="UTF-8"?><metadata>
+ <groupId>uk.co.thebadgerset</groupId>
+ <artifactId>junit-toolkit-maven-plugin</artifactId>
+ <version>0.5-SNAPSHOT</version>
+ <versioning>
+ <snapshot>
+ <timestamp>20070130.111904</timestamp>
+ <buildNumber>1</buildNumber>
+ </snapshot>
+ <lastUpdated>20070130111904</lastUpdated>
+ </versioning>
+</metadata> \ No newline at end of file
diff --git a/java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/0.5-SNAPSHOT/maven-metadata.xml.md5 b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/0.5-SNAPSHOT/maven-metadata.xml.md5
new file mode 100644
index 0000000000..4e7eab390b
--- /dev/null
+++ b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/0.5-SNAPSHOT/maven-metadata.xml.md5
@@ -0,0 +1 @@
+c619b7ac915b2eba622d556b2d2e0c25 \ No newline at end of file
diff --git a/java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/0.5-SNAPSHOT/maven-metadata.xml.sha1 b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/0.5-SNAPSHOT/maven-metadata.xml.sha1
new file mode 100644
index 0000000000..83a5267307
--- /dev/null
+++ b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/0.5-SNAPSHOT/maven-metadata.xml.sha1
@@ -0,0 +1 @@
+db7b5d51a53a5018611391ecc3346032a6c20dda \ No newline at end of file
diff --git a/java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/maven-metadata.xml b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/maven-metadata.xml
new file mode 100644
index 0000000000..a3bff0dde2
--- /dev/null
+++ b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/maven-metadata.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="UTF-8"?><metadata>
+ <groupId>uk.co.thebadgerset</groupId>
+ <artifactId>junit-toolkit-maven-plugin</artifactId>
+ <version>0.5-SNAPSHOT</version>
+ <versioning>
+ <latest>0.5-SNAPSHOT</latest>
+ <versions>
+ <version>0.5-SNAPSHOT</version>
+ </versions>
+ <lastUpdated>20070130111904</lastUpdated>
+ </versioning>
+</metadata> \ No newline at end of file
diff --git a/java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/maven-metadata.xml.md5 b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/maven-metadata.xml.md5
new file mode 100644
index 0000000000..395a968533
--- /dev/null
+++ b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/maven-metadata.xml.md5
@@ -0,0 +1 @@
+da47ce66de64d4ba056d0a9c901c5676 \ No newline at end of file
diff --git a/java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/maven-metadata.xml.sha1 b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/maven-metadata.xml.sha1
new file mode 100644
index 0000000000..b396785e6c
--- /dev/null
+++ b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit-maven-plugin/maven-metadata.xml.sha1
@@ -0,0 +1 @@
+70adf93da1c1757152e954750ceb2477a8659a99 \ No newline at end of file
diff --git a/java/mvn-repo/uk/co/thebadgerset/junit-toolkit/0.5-SNAPSHOT/junit-toolkit-0.5-20070131.112634-1.jar b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit/0.5-SNAPSHOT/junit-toolkit-0.5-20070131.112634-1.jar
new file mode 100644
index 0000000000..d05e42daa0
--- /dev/null
+++ b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit/0.5-SNAPSHOT/junit-toolkit-0.5-20070131.112634-1.jar
Binary files differ
diff --git a/java/mvn-repo/uk/co/thebadgerset/junit-toolkit/0.5-SNAPSHOT/junit-toolkit-0.5-20070131.112634-1.jar.md5 b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit/0.5-SNAPSHOT/junit-toolkit-0.5-20070131.112634-1.jar.md5
new file mode 100644
index 0000000000..fe9db298fb
--- /dev/null
+++ b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit/0.5-SNAPSHOT/junit-toolkit-0.5-20070131.112634-1.jar.md5
@@ -0,0 +1 @@
+b54c1911c914f460a9a816cadd64c787 \ No newline at end of file
diff --git a/java/mvn-repo/uk/co/thebadgerset/junit-toolkit/0.5-SNAPSHOT/junit-toolkit-0.5-20070131.112634-1.jar.sha1 b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit/0.5-SNAPSHOT/junit-toolkit-0.5-20070131.112634-1.jar.sha1
new file mode 100644
index 0000000000..6d93d0b731
--- /dev/null
+++ b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit/0.5-SNAPSHOT/junit-toolkit-0.5-20070131.112634-1.jar.sha1
@@ -0,0 +1 @@
+f150a7450eca6303c94fdad42b59114d6a7d6708 \ No newline at end of file
diff --git a/java/mvn-repo/uk/co/thebadgerset/junit-toolkit/0.5-SNAPSHOT/junit-toolkit-0.5-20070131.112634-1.pom b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit/0.5-SNAPSHOT/junit-toolkit-0.5-20070131.112634-1.pom
new file mode 100644
index 0000000000..7fb4254661
--- /dev/null
+++ b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit/0.5-SNAPSHOT/junit-toolkit-0.5-20070131.112634-1.pom
@@ -0,0 +1,111 @@
+<?xml version="1.0" encoding="UTF-8"?><project>
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>uk.co.thebadgerset</groupId>
+ <artifactId>junit-toolkit</artifactId>
+ <name>junit-toolkit</name>
+ <version>0.5-20070131.112634-1</version>
+ <description>JUnit Toolkit enhances JUnit with performance testing, asymptotic behaviour analysis, and concurrency testing.</description>
+ <url>http://www.thebadgerset.co.uk/junit-toolkit</url>
+ <developers>
+ <developer>
+ <id>rupert</id>
+ <name>Rupert Smith</name>
+ <email>rupertlssmith (contactable on g-m-a-i-l)</email>
+ <organization></organization>
+ </developer>
+ </developers>
+ <licenses>
+ <license>
+ <name>The Apache Software License, Version 2.0</name>
+ <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
+ <distribution>repo</distribution>
+ </license>
+ </licenses>
+ <scm>
+ <connection>scm:svn:http://www.thebadgerset.co.uk/svn/junit-toolkit</connection>
+ </scm>
+ <organization>
+ <name>The Badger Set trading as Liberty Bishop (1151) ltd.</name>
+ <url>http://www.thebadgerset.co.uk/</url>
+ </organization>
+ <build>
+ <sourceDirectory>src/main</sourceDirectory>
+ <pluginManagement>
+ <plugins>
+ <plugin>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <version>2.0.1</version>
+ <configuration>
+ <source>1.5</source>
+ <target>1.5</target>
+ <fork>false</fork>
+ </configuration>
+ </plugin>
+ </plugins>
+ </pluginManagement>
+ </build>
+ <pluginRepositories>
+ <pluginRepository>
+ <snapshots />
+ <id>apache.snapshots</id>
+ <name>Apache SNAPSHOT Repository</name>
+ <url>http://people.apache.org/repo/m2-snapshot-repository</url>
+ </pluginRepository>
+ </pluginRepositories>
+ <dependencies>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>3.8.1</version>
+ </dependency>
+ <dependency>
+ <groupId>log4j</groupId>
+ <artifactId>log4j</artifactId>
+ <version>1.2.8</version>
+ </dependency>
+ <dependency>
+ <groupId>regexp</groupId>
+ <artifactId>regexp</artifactId>
+ <version>1.3</version>
+ </dependency>
+ </dependencies>
+ <reporting>
+ <plugins>
+ <plugin>
+ <artifactId>maven-pmd-plugin</artifactId>
+ <configuration>
+ <linkXref>true</linkXref>
+ <sourceEncoding>utf-8</sourceEncoding>
+ <minimumTokens>20</minimumTokens>
+ <targetJdk>1.5</targetJdk>
+ </configuration>
+ </plugin>
+ <plugin>
+ <artifactId>maven-jxr-plugin</artifactId>
+ </plugin>
+ <plugin>
+ <artifactId>maven-javadoc-plugin</artifactId>
+ </plugin>
+ <plugin>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <configuration>
+ <configLocation>../mavenbuild/coding_standards.xml</configLocation>
+ </configuration>
+ </plugin>
+ </plugins>
+ </reporting>
+ <distributionManagement>
+ <repository>
+ <uniqueVersion>false</uniqueVersion>
+ <id>release-repo</id>
+ <name>The Badger Set Maven2 Repository</name>
+ <url>file://c:/temp</url>
+ </repository>
+ <snapshotRepository>
+ <id>snapshot-repo</id>
+ <name>The Badger Set Maven2 Snapshot Repository</name>
+ <url>file://c:/temp</url>
+ </snapshotRepository>
+ <status>deployed</status>
+ </distributionManagement>
+</project> \ No newline at end of file
diff --git a/java/mvn-repo/uk/co/thebadgerset/junit-toolkit/0.5-SNAPSHOT/junit-toolkit-0.5-20070131.112634-1.pom.md5 b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit/0.5-SNAPSHOT/junit-toolkit-0.5-20070131.112634-1.pom.md5
new file mode 100644
index 0000000000..73d40e036e
--- /dev/null
+++ b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit/0.5-SNAPSHOT/junit-toolkit-0.5-20070131.112634-1.pom.md5
@@ -0,0 +1 @@
+7f48b1816a77acb427ad5dcb2b1eb5bb \ No newline at end of file
diff --git a/java/mvn-repo/uk/co/thebadgerset/junit-toolkit/0.5-SNAPSHOT/junit-toolkit-0.5-20070131.112634-1.pom.sha1 b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit/0.5-SNAPSHOT/junit-toolkit-0.5-20070131.112634-1.pom.sha1
new file mode 100644
index 0000000000..dec86a3286
--- /dev/null
+++ b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit/0.5-SNAPSHOT/junit-toolkit-0.5-20070131.112634-1.pom.sha1
@@ -0,0 +1 @@
+5fece706dc17a5d30acad3135ea67f6b9229a6d4 \ No newline at end of file
diff --git a/java/mvn-repo/uk/co/thebadgerset/junit-toolkit/0.5-SNAPSHOT/maven-metadata.xml b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit/0.5-SNAPSHOT/maven-metadata.xml
new file mode 100644
index 0000000000..216800cda7
--- /dev/null
+++ b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit/0.5-SNAPSHOT/maven-metadata.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="UTF-8"?><metadata>
+ <groupId>uk.co.thebadgerset</groupId>
+ <artifactId>junit-toolkit</artifactId>
+ <version>0.5-SNAPSHOT</version>
+ <versioning>
+ <snapshot>
+ <timestamp>20070131.112634</timestamp>
+ <buildNumber>1</buildNumber>
+ </snapshot>
+ <lastUpdated>20070131112634</lastUpdated>
+ </versioning>
+</metadata> \ No newline at end of file
diff --git a/java/mvn-repo/uk/co/thebadgerset/junit-toolkit/0.5-SNAPSHOT/maven-metadata.xml.md5 b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit/0.5-SNAPSHOT/maven-metadata.xml.md5
new file mode 100644
index 0000000000..c355e8f9be
--- /dev/null
+++ b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit/0.5-SNAPSHOT/maven-metadata.xml.md5
@@ -0,0 +1 @@
+59aa948e74a22a370cc414718864f65f \ No newline at end of file
diff --git a/java/mvn-repo/uk/co/thebadgerset/junit-toolkit/0.5-SNAPSHOT/maven-metadata.xml.sha1 b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit/0.5-SNAPSHOT/maven-metadata.xml.sha1
new file mode 100644
index 0000000000..5d9fbad25f
--- /dev/null
+++ b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit/0.5-SNAPSHOT/maven-metadata.xml.sha1
@@ -0,0 +1 @@
+f2350021d6d3c2091d35d074b6ecd312d6f91657 \ No newline at end of file
diff --git a/java/mvn-repo/uk/co/thebadgerset/junit-toolkit/maven-metadata.xml b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit/maven-metadata.xml
new file mode 100644
index 0000000000..4ee3d61cca
--- /dev/null
+++ b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit/maven-metadata.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="UTF-8"?><metadata>
+ <groupId>uk.co.thebadgerset</groupId>
+ <artifactId>junit-toolkit</artifactId>
+ <version>0.5-SNAPSHOT</version>
+ <versioning>
+ <versions>
+ <version>0.5-SNAPSHOT</version>
+ </versions>
+ <lastUpdated>20070131112634</lastUpdated>
+ </versioning>
+</metadata> \ No newline at end of file
diff --git a/java/mvn-repo/uk/co/thebadgerset/junit-toolkit/maven-metadata.xml.md5 b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit/maven-metadata.xml.md5
new file mode 100644
index 0000000000..39d7b84744
--- /dev/null
+++ b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit/maven-metadata.xml.md5
@@ -0,0 +1 @@
+260c92993eec99c2c2c0217cf6241842 \ No newline at end of file
diff --git a/java/mvn-repo/uk/co/thebadgerset/junit-toolkit/maven-metadata.xml.sha1 b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit/maven-metadata.xml.sha1
new file mode 100644
index 0000000000..bc3857fa21
--- /dev/null
+++ b/java/mvn-repo/uk/co/thebadgerset/junit-toolkit/maven-metadata.xml.sha1
@@ -0,0 +1 @@
+c8803f171049b2bb3e258f78b8c9490dec3074c4 \ No newline at end of file
diff --git a/java/mvn-repo/uk/co/thebadgerset/maven-metadata.xml b/java/mvn-repo/uk/co/thebadgerset/maven-metadata.xml
new file mode 100644
index 0000000000..4c367f55d3
--- /dev/null
+++ b/java/mvn-repo/uk/co/thebadgerset/maven-metadata.xml
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="UTF-8"?><metadata>
+ <plugins>
+ <plugin>
+ <name>junit-toolkit-maven-plugin</name>
+ <prefix>junit-toolkit</prefix>
+ <artifactId>junit-toolkit-maven-plugin</artifactId>
+ </plugin>
+ </plugins>
+</metadata> \ No newline at end of file
diff --git a/java/mvn-repo/uk/co/thebadgerset/maven-metadata.xml.md5 b/java/mvn-repo/uk/co/thebadgerset/maven-metadata.xml.md5
new file mode 100644
index 0000000000..da122e37da
--- /dev/null
+++ b/java/mvn-repo/uk/co/thebadgerset/maven-metadata.xml.md5
@@ -0,0 +1 @@
+8eee1c76f27e4d20ffcd48d87897b923 \ No newline at end of file
diff --git a/java/mvn-repo/uk/co/thebadgerset/maven-metadata.xml.sha1 b/java/mvn-repo/uk/co/thebadgerset/maven-metadata.xml.sha1
new file mode 100644
index 0000000000..fd57ffc943
--- /dev/null
+++ b/java/mvn-repo/uk/co/thebadgerset/maven-metadata.xml.sha1
@@ -0,0 +1 @@
+300ebe0bfa8ae2b56d26a9fae9073ef9f902b0e7 \ No newline at end of file
diff --git a/java/perftests/RunningPerformanceTests.txt b/java/perftests/RunningPerformanceTests.txt
new file mode 100644
index 0000000000..ff3d5ef4f5
--- /dev/null
+++ b/java/perftests/RunningPerformanceTests.txt
@@ -0,0 +1,112 @@
+Running Performance Tests
+-------------------------
+
+This performance test suite contains a number of tests.
+
+- Service request-reply
+- Ping-Pong
+- Topic
+
+Service request-reply
+---------------------
+
+Description:
+This is the simplest test to ensure everything is working. This involves
+one client that is known as a "service provider" and it listens on a
+well-known queue for requests. Another client, known as the "service requester"
+creates a private (temporary) response queue, creates a message with the
+private response queue set as the "reply to" field and then publishes the
+message to the well known service queue. The test allows you to time how long
+it takes to send messages and receive the response back. It also allows varying
+of the message size.
+
+Quick Run:
+
+./serviceRequestReply-QuickTest.sh <brokerdetails> <number of messages>
+
+This provides a quick test to run everything against a running broker. Simply specify broker and number of messages to run.
+
+
+Detailed Run:
+
+You must start the service provider first:
+
+serviceProvidingClient.sh <brokerdetails> [<P[ersistent]|N[onPersistent]> <T[ransacted]|N[onTransacted]>] [selector]
+
+where Brokerdetails is the connection information to the broker you are running on; e.g. localhost or localhost:5670 or tcp://10.10.10.10:5677.
+By default Non Persistent, Non Transaction messages are used in the response. A selector may also be specified.
+
+
+To run the service requester:
+
+serviceRequestingClient.sh <Brokerdetails> <Number of Messages> [<Message Size>] [<P[ersistent]|N[onPersistent]> <T[ransacted]|N[onTransacted]>]
+
+This requests the <number of messages> of a <Message Size (default 4096 bytes>. By default the connection is Non Persistent and Non Transactional.
+
+After receiving all the messages the client outputs the rate it achieved.
+
+
+Ping-Pong
+---------
+
+Description:
+Quick Run:
+Detailed Run:
+
+Topic
+-------
+
+Description:
+A more realistic test is the topic test, which tests the
+performance of the topic exchange to a configurable number of clients (e.g. 50).
+A publisher sends batches of of messages to a topic that a number of clients are
+subscribed to. The clients recevie each all the messages and then send a response.
+
+The time taken to send all messages and receive a response from all clients is displayed.
+
+Quick Run:
+
+./topic-QuickTest.sh <host> <port> <messages> <clients> <batches>
+
+This provides a quick test to run everything against a running broker. Simply specify host, port, the number of messages, number of clients and number of batches to run this quick test.
+
+Detailed Run:
+
+You must run the listener processes first:
+
+run_many.sh 10 topic "topicListener.sh [-host <host> -port <port>]"
+
+In this command, the first argument means start 10 processes, the
+second is just a name use in the log files generated and the third
+argument is the command to run the specified number of times.
+
+The topicListener by default connects to localhost:5672 this can be changed using the above flags.
+
+Then run the publisher process:
+
+headersPublisher.sh [-host <host> -port <port> -messages <number> -clients <number> -batch <number>]
+
+The default is to connect to localhost:5672 and send 1 batch of 1000 messages expecting 1 client to respond.
+
+Note that before starting the publisher you should wait about 30
+seconds to ensure all the clients are registered with the broker (you
+can see this from the broker output). Otherwise the numbers will be
+slightly skewed.
+
+
+Additional parameters to scripts
+
+Publisher
+-payload <int> : specify the payload size (256b Default)
+-delay <long> : Number of seconds to send between batches (0 Default)
+-warmup <int> : Number of messages to send as a warm up (0 Default)
+-ack <int> : Acknowledgement mode
+ - 1 : Auto
+ - 2 : Client
+ - 3 : Dups_OK
+ - 257 : No (Default)
+ - 258 : Pre
+-factory <string> : ConnectionFactoryInitialiser class
+-persistent <"true"|other> : User persistent messages if string equals "true" (false Default)
+-clientId <string> : Set client id
+-subscriptionId <string> : set subscription id
diff --git a/java/perftests/bin/run_many.sh b/java/perftests/bin/run_many.sh
deleted file mode 100755
index cca2ffec21..0000000000
--- a/java/perftests/bin/run_many.sh
+++ /dev/null
@@ -1,30 +0,0 @@
-#!/bin/sh
-#
-# 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.
-#
-
-
-# args:
-# <number of processes to start>
-# <name of run>
-# <command ro run>
-
-for i in `seq 1 $1`; do
- $3 >$2.$i.out 2>>$2.err &
- echo $! > $2.$i.pid
-done;
diff --git a/java/perftests/bin/serviceProvidingClient.sh b/java/perftests/bin/serviceProvidingClient.sh
deleted file mode 100755
index 207e4439f1..0000000000
--- a/java/perftests/bin/serviceProvidingClient.sh
+++ /dev/null
@@ -1,25 +0,0 @@
-#!/bin/bash
-#
-# 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.
-#
-
-# XXX -Xms1024m -XX:NewSize=300m
-. ./setupclasspath.sh
-echo $CP
-# usage: just pass in the host(s)
-$JAVA_HOME/bin/java -cp $CP org.apache.qpid.requestreply.ServiceProvidingClient $1 guest guest /test serviceQ
diff --git a/java/perftests/bin/serviceRequestingClient.sh b/java/perftests/bin/serviceRequestingClient.sh
deleted file mode 100755
index 7dd3d63c27..0000000000
--- a/java/perftests/bin/serviceRequestingClient.sh
+++ /dev/null
@@ -1,27 +0,0 @@
-#!/bin/bash
-#
-# 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.
-#
-# args supplied: <host:port> <num messages>
-thehosts=$1
-shift
-echo $thehosts
-# XXX -Xms1024m -XX:NewSize=300m
-. ./setupclasspath.sh
-echo $CP
-$JAVA_HOME/bin/java -cp $CP -Damqj.logging.level="INFO" org.apache.qpid.requestreply.ServiceRequestingClient $thehosts guest guest /test serviceQ "$@"
diff --git a/java/perftests/bin/setupclasspath.sh b/java/perftests/bin/setupclasspath.sh
deleted file mode 100755
index a660392e77..0000000000
--- a/java/perftests/bin/setupclasspath.sh
+++ /dev/null
@@ -1,9 +0,0 @@
-if [ -z $QPID_HOME ] ; then
- echo "QPID_HOME must be set"
- exit
-fi
-CP=$QPID_HOME/lib/qpid-incubating.jar:../target/classes
-
-if [ `uname -o` == "Cygwin" ] ; then
- CP=`cygpath --path --windows $CP`
-fi
diff --git a/java/perftests/distribution/pom.xml b/java/perftests/distribution/pom.xml
new file mode 100644
index 0000000000..010f19c9f0
--- /dev/null
+++ b/java/perftests/distribution/pom.xml
@@ -0,0 +1,127 @@
+<!--
+ 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.
+ -->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>org.apache.qpid</groupId>
+ <artifactId>qpid-perftests-distribution</artifactId>
+ <packaging>jar</packaging>
+ <version>1.0-incubating-M2-SNAPSHOT</version>
+ <name>Qpid Performance Tests Distribution</name>
+ <url>http://cwiki.apache.org/confluence/display/qpid</url>
+
+ <parent>
+ <groupId>org.apache.qpid</groupId>
+ <artifactId>qpid</artifactId>
+ <version>1.0-incubating-M2-SNAPSHOT</version>
+ </parent>
+
+ <properties>
+ <topDirectoryLocation>..</topDirectoryLocation>
+ <java.source.version>1.5</java.source.version>
+ <qpid.version>${pom.version}</qpid.version>
+ <qpid.targetDir>${project.build.directory}</qpid.targetDir>
+ </properties>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.qpid</groupId>
+ <artifactId>qpid-perftests</artifactId>
+ <type>jar</type>
+ <version>${pom.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.qpid</groupId>
+ <artifactId>qpid-perftests</artifactId>
+ <type>test-jar</type>
+ <version>${pom.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>uk.co.thebadgerset</groupId>
+ <artifactId>junit-toolkit</artifactId>
+ <version>0.4</version>
+ <scope>runtime</scope>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <pluginManagement>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <configuration>
+ <source>${java.source.version}</source>
+ <target>${java.source.version}</target>
+ </configuration>
+ </plugin>
+
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-assembly-plugin</artifactId>
+ <version>${assembly.version}</version>
+ <configuration>
+ <descriptors>
+ <descriptor>src/main/assembly/performance.xml</descriptor>
+ </descriptors>
+ <finalName>qpid-${pom.version}</finalName>
+ <outputDirectory>${qpid.targetDir}</outputDirectory>
+ <tarLongFileMode>gnu</tarLongFileMode>
+ </configuration>
+ </plugin>
+
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-jar-plugin</artifactId>
+ <configuration>
+ <finalName>qpid-performance</finalName>
+ <archive>
+ <manifest>
+ <addClasspath>true</addClasspath>
+ </manifest>
+ </archive>
+ </configuration>
+ </plugin>
+ </plugins>
+ </pluginManagement>
+
+ <plugins>
+ <plugin>
+ <artifactId>maven-assembly-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>distribution-package</id>
+ <phase>package</phase>
+ <goals>
+ <goal>single</goal>
+ </goals>
+ <configuration>
+ <descriptors>
+ <descriptor>src/main/assembly/performance.xml</descriptor>
+ </descriptors>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+
+ </build>
+
+</project>
diff --git a/java/perftests/distribution/src/main/assembly/performance.xml b/java/perftests/distribution/src/main/assembly/performance.xml
new file mode 100644
index 0000000000..a564261a24
--- /dev/null
+++ b/java/perftests/distribution/src/main/assembly/performance.xml
@@ -0,0 +1,103 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ * 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.
+-->
+<assembly>
+ <id>performance-test-java</id>
+ <includeBaseDirectory>false</includeBaseDirectory>
+ <formats>
+ <format>tar.gz</format>
+ <format>zip</format>
+ </formats>
+
+ <fileSets>
+ <!-- Apache Licensing -->
+ <fileSet>
+ <directory>../../resources</directory>
+ <outputDirectory>qpid-${qpid.version}</outputDirectory>
+ <includes>
+ <include>DISCLAIMER</include>
+ <include>LICENSE.txt</include>
+ <include>NOTICE.txt</include>
+ <include>README.txt</include>
+ </includes>
+ </fileSet>
+
+ <fileSet>
+ <directory>../../release-docs</directory>
+ <outputDirectory>qpid-${qpid.version}/docs</outputDirectory>
+ <includes>
+ <include>RELEASE_NOTES.txt</include>
+ </includes>
+ </fileSet>
+
+ <!-- Performance txt files-->
+ <fileSet>
+ <directory>..</directory>
+ <outputDirectory>qpid-${qpid.version}</outputDirectory>
+ <includes>
+ <include>*.txt</include>
+ </includes>
+ </fileSet>
+
+ <!-- Execution Scripts -->
+ <fileSet>
+ <directory>../bin</directory>
+ <outputDirectory>qpid-${qpid.version}/bin</outputDirectory>
+ <includes>
+ <include>*</include>
+ </includes>
+ <fileMode>777</fileMode>
+ </fileSet>
+
+ <!-- Provide Source in easy access location -->
+ <fileSet>
+ <directory>../src/main</directory>
+ <outputDirectory>qpid-${qpid.version}/src</outputDirectory>
+ <includes>
+ <include>**/*.java</include>
+ <include>**/*.log4j</include>
+ </includes>
+ </fileSet>
+ <fileSet>
+ <directory>../src/test</directory>
+ <outputDirectory>qpid-${qpid.version}/src</outputDirectory>
+ <includes>
+ <include>**/*.java</include>
+ </includes>
+ </fileSet>
+
+ <!-- Metadata Jar -->
+ <fileSet>
+ <directory>target</directory>
+ <outputDirectory>qpid-${qpid.version}/lib</outputDirectory>
+ <includes>
+ <include>qpid-performance.jar</include>
+ </includes>
+ </fileSet>
+ </fileSets>
+ <dependencySets>
+ <dependencySet>
+ <outputDirectory>qpid-${qpid.version}/lib</outputDirectory>
+ <unpack>false</unpack>
+ <excludes>
+ <exclude>org.apache.qpid:qpid-perftests-distribution</exclude>
+ </excludes>
+ </dependencySet>
+ </dependencySets>
+</assembly>
diff --git a/java/perftests/jar-with-dependencies.xml b/java/perftests/jar-with-dependencies.xml
new file mode 100644
index 0000000000..62978ee864
--- /dev/null
+++ b/java/perftests/jar-with-dependencies.xml
@@ -0,0 +1,29 @@
+<!-- This is an assembly descriptor that produces a jar file that contains all the
+ dependencies, fully expanded into a single jar, required to run the tests of
+ a maven project.
+ -->
+<assembly>
+ <id>all-test-deps</id>
+ <formats>
+ <format>jar</format>
+ </formats>
+ <includeBaseDirectory>false</includeBaseDirectory>
+ <dependencySets>
+ <dependencySet>
+ <outputDirectory></outputDirectory>
+ <outputFileNameMapping></outputFileNameMapping>
+ <unpack>true</unpack>
+ <scope>test</scope>
+ </dependencySet>
+ </dependencySets>
+ <fileSets>
+ <fileSet>
+ <directory>target/classes</directory>
+ <outputDirectory></outputDirectory>
+ </fileSet>
+ <fileSet>
+ <directory>target/test-classes</directory>
+ <outputDirectory></outputDirectory>
+ </fileSet>
+ </fileSets>
+</assembly>
diff --git a/java/perftests/pom.xml b/java/perftests/pom.xml
index 3af906c4ac..758678fc84 100644
--- a/java/perftests/pom.xml
+++ b/java/perftests/pom.xml
@@ -19,6 +19,7 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
<modelVersion>4.0.0</modelVersion>
<groupId>org.apache.qpid</groupId>
<artifactId>qpid-perftests</artifactId>
@@ -35,21 +36,219 @@
<properties>
<topDirectoryLocation>..</topDirectoryLocation>
+ <log4j.perftests>perftests.log4j</log4j.perftests>
</properties>
+ <!-- Temporary local maven repo, whilst JUnit Toolkit is still reaching stable version to add to central maven repository. -->
+ <repositories>
+ <repository>
+ <id>junit-toolkit.snapshots</id>
+ <name>JUnit Toolkit SNAPSHOT Repository</name>
+ <url>file://${basedir}/../mvn-repo</url>
+ <snapshots>
+ <enabled>true</enabled>
+ </snapshots>
+ </repository>
+ </repositories>
+
+ <!-- Temporary local maven repo, whilst JUnit Toolkit is still reaching stable version to add to central maven repository. -->
+ <pluginRepositories>
+ <pluginRepository>
+ <id>junit-toolkit-plugin.snapshots</id>
+ <name>JUnit Toolkit SNAPSHOT Repository</name>
+ <url>file://${basedir}/../mvn-repo</url>
+ <snapshots>
+ <enabled>true</enabled>
+ </snapshots>
+ </pluginRepository>
+ </pluginRepositories>
+
<dependencies>
+
<dependency>
<groupId>org.apache.qpid</groupId>
<artifactId>qpid-client</artifactId>
</dependency>
+
+ <dependency>
+ <groupId>log4j</groupId>
+ <artifactId>log4j</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>uk.co.thebadgerset</groupId>
+ <artifactId>junit-toolkit</artifactId>
+ </dependency>
+
+ <!-- Test dependencies. -->
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </dependency>
+
</dependencies>
-<!-- <build>
+ <build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
</plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-plugin</artifactId>
+ </plugin>
+
+ <!-- The JUnit Toolkit maven2 plugin is in the process of being added to the maven repository.
+
+ Configures the toolkit test runner for performance testing. These can be run from within maven, or by using the generated
+ scripts.
+
+ To run from within maven:
+
+ mvn uk.co.thebadgerset:junit-toolkit-maven-plugin:tktest
+
+ To run from the command line (after doing assembly:assembly goal):
+
+ java -cp target/test_jar-jar-with-dependencies.jar uk.co.thebadgerset.junit.extensions.TKTestRunner -s 1 -r 100000
+ -o target org.apache.qpid.requestreply.PingPongTestPerf
+
+ To generate the scripts do:
+
+ mvn uk.co.thebadgerset:junit-toolkit-maven-plugin:tkscriptgen
+
+ Then to run the scripts, in the target directory do (after doing assembly:assembly goal):
+
+ ./script_name.sh
+
+ These scripts can find everything in the 'all test dependencies' jar created by the assembly:assembly goal.
+ -->
+ <plugin>
+ <groupId>uk.co.thebadgerset</groupId>
+ <artifactId>junit-toolkit-maven-plugin</artifactId>
+
+ <configuration>
+ <scriptOutDirectory>target</scriptOutDirectory>
+ <testJar>${project.build.finalName}-all-test-deps.jar</testJar>
+
+ <systemproperties>
+ <property>
+ <name>log4j.configuration</name>
+ <value>${log4j.perftests}</value>
+ </property>
+ <property>
+ <name>amqj.logging.level</name>
+ <value>warn</value>
+ </property>
+ <property><!-- Turn off most logging messages from the junit-toolkit test tool itself. -->
+ <name>badger.level</name>
+ <value>warn</value>
+ </property>
+ <property>
+ <name>amqj.test.logging.level</name>
+ <value>info</value>
+ </property>
+ </systemproperties>
+
+ <commands>
+ <!-- Single pings. These can be scaled up by overriding the parameters when calling the test script. -->
+ <Ping-Once>-n Ping-Once -s [1] -r 1 -t testPingOk -o . org.apache.qpid.ping.PingTestPerf</Ping-Once>
+ <Ping-Once-Async>-n Ping-Once-Async -s [1] -r 1 -t testAsyncPingOk -o . org.apache.qpid.ping.PingAsyncTestPerf</Ping-Once-Async>
+ <Ping-Latency>-n Ping-Latency -s [1000] -d 10S -t testPingLatency -o . org.apache.qpid.ping.PingLatencyTestPerf</Ping-Latency>
+
+ <!-- More example Tests. These are examples to exercise all the features of the test harness. Can scale up with option overrides. -->
+ <Ping-Tx>-n Ping-Tx -s [100] -o . -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf transacted=true</Ping-Tx>
+ <Ping-Size>-n Ping-Size -s [100] -o . -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf messagesize=512</Ping-Size>
+ <Ping-Concurrent>-n Ping-Concurrent -s [100] -c [4] -o . -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf</Ping-Concurrent>
+ <Ping-Many-Queues>
+ -n Ping-Many-Queues -s [100] -o . -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf destinationcount=4
+ </Ping-Many-Queues>
+ <Ping-Duration>-n Ping-Duration -s [100] -d10S -o . -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf</Ping-Duration>
+ <Ping-Rate>-n Ping-Rate -s [100] -d10S -o . -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf rate=500</Ping-Rate>
+ <Ping-PubSub>-n Ping-PubSub -s [100] -o . -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf pubsub=true</Ping-PubSub>
+ <Ping-Many-Topics>
+ -n Ping-Many-Topics -s [100] -o . -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf pubsub=true destinationcount=4
+ </Ping-Many-Topics>
+ <Ping-Persistent>
+ -n Ping-Persistent -s [100] -o . -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf persistent=true
+ </Ping-Persistent>
+ <Ping-Batch-Logging>
+ -n Ping-Batch-Logging -s [100] -o . -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf BatchSize=10
+ </Ping-Batch-Logging>
+ <Ping-Failover-Before-Send>
+ -n Ping-Failover-Before-Send -s [100] -o . -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf CommitBatchSize=10 FailBeforeSend=true
+ </Ping-Failover-Before-Send>
+ <Ping-Failover-After-Send>
+ -n Ping-Failover-After-Send -s [100] -o . -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf CommitBatchSize=10 FailAfterSend=true
+ </Ping-Failover-After-Send>
+ <Ping-Failover-Before-Commit>
+ -n Ping-Failover-Before-Commit -s [100] -o . -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf CommitBatchSize=10 FailBeforeCommit=true
+ </Ping-Failover-Before-Commit>
+ <Ping-Failover-After-Commit>
+ -n Ping-Failover-After-Commit -s [100] -o . -t testAsyncPingOk org.apache.qpid.ping.PingAsyncTestPerf CommitBatchSize=10 FailAfterCommit=true
+ </Ping-Failover-After-Commit>
+
+ </commands>
+ </configuration>
+
+ <executions>
+ <execution>
+ <phase>test</phase>
+ <!--<goals>
+ <goal>tktest</goal>
+ </goals>-->
+ </execution>
+ </executions>
+ </plugin>
+
+ <!-- Bundles all the dependencies, fully expanded into a single jar, required to run the tests.
+
+ Usefull when bundling system, integration or performance tests into a convenient
+ package to hand over to testers. To use it run:
+
+ java -cp target/your_app_name-all-test-deps.jar path.to.your.Class
+
+ or often:
+
+ java -cp target/your_app_name-all-test-deps.jar junit.framework.textui.TestRunner path.to.your.test.Class
+
+ or other JUnit test runner invocations.
+ -->
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-assembly-plugin</artifactId>
+ <version>2.2-SNAPSHOT</version>
+ <configuration>
+ <descriptors>
+ <descriptor>jar-with-dependencies.xml</descriptor>
+ </descriptors>
+ <outputDirectory>target</outputDirectory>
+ <workDirectory>target/assembly/work</workDirectory>
+ </configuration>
+ </plugin>
+
</plugins>
- </build>-->
+
+ <resources>
+ <!-- Include source files in built jar -->
+ <resource>
+ <targetPath>src/</targetPath>
+ <filtering>false</filtering>
+ <directory>src/main/java</directory>
+ <includes>
+ <include>**/*.java</include>
+ </includes>
+ </resource>
+ <!-- Include a log4j configuration in the jar at the root level (don't name this log4j.properties though as won't be able to override it). -->
+ <resource>
+ <targetPath>/</targetPath>
+ <filtering>false</filtering>
+ <directory>src/main/java</directory>
+ <includes>
+ <include>perftests.log4j</include>
+ </includes>
+ </resource>
+ </resources>
+ </build>
+
</project>
diff --git a/java/perftests/src/main/java/org/apache/qpid/client/message/TestMessageFactory.java b/java/perftests/src/main/java/org/apache/qpid/client/message/TestMessageFactory.java
new file mode 100644
index 0000000000..c0f236b833
--- /dev/null
+++ b/java/perftests/src/main/java/org/apache/qpid/client/message/TestMessageFactory.java
@@ -0,0 +1,118 @@
+/*
+ *
+ * Copyright (c) 2006 The Apache Software Foundation
+ *
+ * Licensed 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.client.message;
+
+import org.apache.mina.common.ByteBuffer;
+import org.apache.mina.common.SimpleByteBufferAllocator;
+
+import javax.jms.JMSException;
+import javax.jms.Session;
+import javax.jms.ObjectMessage;
+import javax.jms.StreamMessage;
+import javax.jms.BytesMessage;
+import javax.jms.TextMessage;
+import javax.jms.Queue;
+import javax.jms.DeliveryMode;
+import javax.jms.Destination;
+
+public class TestMessageFactory
+{
+ private static final String MESSAGE_DATA_BYTES = "-message payload-message paylaod-message payload-message paylaod";
+
+ public static TextMessage newTextMessage(Session session, int size) throws JMSException
+ {
+ return session.createTextMessage(createMessagePayload(size));
+ }
+
+ public static JMSTextMessage newJMSTextMessage(int size, String encoding) throws JMSException
+ {
+ ByteBuffer byteBuffer = (new SimpleByteBufferAllocator()).allocate(size, true);
+ JMSTextMessage message = new JMSTextMessage(byteBuffer, encoding);
+ message.clearBody();
+ message.setText(createMessagePayload(size));
+ return message;
+ }
+
+ public static BytesMessage newBytesMessage(Session session, int size) throws JMSException
+ {
+ BytesMessage message = session.createBytesMessage();
+ message.writeUTF(createMessagePayload(size));
+ return message;
+ }
+
+ public static StreamMessage newStreamMessage(Session session, int size) throws JMSException
+ {
+ StreamMessage message = session.createStreamMessage();
+ message.writeString(createMessagePayload(size));
+ return message;
+ }
+
+ public static ObjectMessage newObjectMessage(Session session, int size) throws JMSException
+ {
+ if (size == 0)
+ {
+ return session.createObjectMessage();
+ }
+ else
+ {
+ return session.createObjectMessage(createMessagePayload(size));
+ }
+ }
+
+ /**
+ * Creates an ObjectMessage with given size and sets the JMS properties (JMSReplyTo and DeliveryMode)
+ * @param session
+ * @param replyDestination
+ * @param size
+ * @param persistent
+ * @return the new ObjectMessage
+ * @throws JMSException
+ */
+ public static ObjectMessage newObjectMessage(Session session, Destination replyDestination, int size, boolean persistent) throws JMSException
+ {
+ ObjectMessage msg = newObjectMessage(session, size);
+
+ // Set the messages persistent delivery flag.
+ msg.setJMSDeliveryMode(persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT);
+
+ // Ensure that the temporary reply queue is set as the reply to destination for the message.
+ if (replyDestination != null)
+ {
+ msg.setJMSReplyTo(replyDestination);
+ }
+
+ return msg;
+ }
+
+ public static String createMessagePayload(int size)
+ {
+ StringBuffer buf = new StringBuffer(size);
+ int count = 0;
+ while (count < size)
+ {
+ buf.append(MESSAGE_DATA_BYTES);
+ count += MESSAGE_DATA_BYTES.length();
+ }
+ if (count < size)
+ {
+ buf.append(MESSAGE_DATA_BYTES, 0, size - count);
+ }
+
+ return buf.toString();
+ }
+}
diff --git a/java/perftests/src/main/java/org/apache/qpid/ping/PingClient.java b/java/perftests/src/main/java/org/apache/qpid/ping/PingClient.java
new file mode 100644
index 0000000000..7fd91ca39d
--- /dev/null
+++ b/java/perftests/src/main/java/org/apache/qpid/ping/PingClient.java
@@ -0,0 +1,90 @@
+/*
+ *
+ * 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.ping;
+
+import java.util.List;
+
+import javax.jms.Destination;
+
+import org.apache.qpid.requestreply.PingPongProducer;
+
+/**
+ * PingClient is a {@link PingPongProducer} that does not need a {@link org.apache.qpid.requestreply.PingPongBouncer}
+ * to send replies to its pings. It simply listens to its own ping destinations, rather than seperate reply queues.
+ * It is an all in one ping client, that produces and consumes its own pings.
+ *
+ * <p/><table id="crc"><caption>CRC Card</caption>
+ * <tr><th> Responsibilities <th> Collaborations
+ * <tr><td> Create a ping pong producer that listens to its own pings <td> {@link PingPongProducer}
+ * </table>
+ */
+public class PingClient extends PingPongProducer
+{
+ /**
+ * Creates a ping producer with the specified parameters, of which there are many. See their individual comments
+ * for details. This constructor creates ping pong producer but de-registers its reply-to destination message
+ * listener, and replaces it by listening to all of its ping destinations.
+ *
+ * @param brokerDetails The URL of the broker to send pings to.
+ * @param username The username to log onto the broker with.
+ * @param password The password to log onto the broker with.
+ * @param virtualpath The virtual host name to use on the broker.
+ * @param destinationName The name (or root where multiple destinations are used) of the desitination to send
+ * pings to.
+ * @param selector The selector to filter replies with.
+ * @param transacted Indicates whether or not pings are sent and received in transactions.
+ * @param persistent Indicates whether pings are sent using peristent delivery.
+ * @param messageSize Specifies the size of ping messages to send.
+ * @param verbose Indicates that information should be printed to the console on every ping.
+ * @param afterCommit Indicates that the user should be promted to terminate a broker after commits to test failover.
+ * @param beforeCommit Indicates that the user should be promted to terminate a broker before commits to test failover.
+ * @param afterSend Indicates that the user should be promted to terminate a broker after sends to test failover.
+ * @param beforeSend Indicates that the user should be promted to terminate a broker before sends to test failover.
+ * @param failOnce Indicates that the failover testing behaviour should only happen on the first commit, not all.
+ * @param txBatchSize Specifies the number of pings to send in each transaction.
+ * @param noOfDestinations The number of destinations to ping. Must be 1 or more.
+ * @param rate Specified the number of pings per second to send. Setting this to 0 means send as fast as
+ * possible, with no rate restriction.
+ * @param pubsub
+ *
+ * @throws Exception Any exceptions are allowed to fall through.
+ */
+ public PingClient(String brokerDetails, String username, String password, String virtualpath, String destinationName,
+ String selector, boolean transacted, boolean persistent, int messageSize, boolean verbose,
+ boolean afterCommit, boolean beforeCommit, boolean afterSend, boolean beforeSend, boolean failOnce,
+ int txBatchSize, int noOfDestinations, int rate, boolean pubsub) throws Exception
+ {
+ super(brokerDetails, username, password, virtualpath, destinationName, selector, transacted, persistent, messageSize,
+ verbose, afterCommit, beforeCommit, afterSend, beforeSend, failOnce, txBatchSize, noOfDestinations, rate,
+ pubsub);
+ }
+
+ /**
+ * Returns the ping destinations themselves as the reply destinations for this pinger to listen to. This has the
+ * effect of making this pinger listen to its own pings.
+ *
+ * @return The ping destinations.
+ */
+ public List<Destination> getReplyDestinations()
+ {
+ return _pingDestinations;
+ }
+}
diff --git a/java/perftests/src/main/java/org/apache/qpid/requestreply/PingPongBouncer.java b/java/perftests/src/main/java/org/apache/qpid/requestreply/PingPongBouncer.java
new file mode 100644
index 0000000000..87edd31575
--- /dev/null
+++ b/java/perftests/src/main/java/org/apache/qpid/requestreply/PingPongBouncer.java
@@ -0,0 +1,452 @@
+/*
+ *
+ * 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.requestreply;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+import javax.jms.*;
+
+import org.apache.log4j.Logger;
+
+import org.apache.qpid.client.AMQConnection;
+import org.apache.qpid.client.AMQQueue;
+import org.apache.qpid.client.AMQTopic;
+import org.apache.qpid.jms.ConnectionListener;
+import org.apache.qpid.jms.Session;
+import org.apache.qpid.topic.Config;
+
+/**
+ * PingPongBouncer is a message listener the bounces back messages to their reply to destination. This is used to return
+ * ping messages generated by {@link org.apache.qpid.requestreply.PingPongProducer} but could be used for other purposes
+ * too.
+ *
+ * <p/>The correlation id from the received message is extracted, and placed into the reply as the correlation id. Messages
+ * are bounced back to their reply-to destination. The original sender of the message has the option to use either a unique
+ * temporary queue or the correlation id to correlate the original message to the reply.
+ *
+ * <p/>There is a verbose mode flag which causes information about each ping to be output to the console
+ * (info level logging, so usually console). This can be helpfull to check the bounce backs are happening but should
+ * be disabled for real timing tests as writing to the console will slow things down.
+ *
+ * <p><table id="crc"><caption>CRC Card</caption>
+ * <tr><th> Responsibilities <th> Collaborations
+ * <tr><td> Bounce back messages to their reply to destination.
+ * <tr><td> Provide command line invocation to start the bounce back on a configurable broker url.
+ * </table>
+ *
+ * @todo Replace the command line parsing with a neater tool.
+ *
+ * @todo Make verbose accept a number of messages, only prints to console every X messages.
+ */
+public class PingPongBouncer implements MessageListener
+{
+ private static final Logger _logger = Logger.getLogger(PingPongBouncer.class);
+
+ /** The default prefetch size for the message consumer. */
+ private static final int PREFETCH = 1;
+
+ /** The default no local flag for the message consumer. */
+ private static final boolean NO_LOCAL = true;
+
+ private static final String DEFAULT_DESTINATION_NAME = "ping";
+
+ /** The default exclusive flag for the message consumer. */
+ private static final boolean EXCLUSIVE = false;
+
+ /** A convenient formatter to use when time stamping output. */
+ protected static final SimpleDateFormat timestampFormatter = new SimpleDateFormat("hh:mm:ss:SS");
+
+ /** Used to indicate that the reply generator should log timing info to the console (logger info level). */
+ private boolean _verbose = false;
+
+ /** Determines whether this bounce back client bounces back messages persistently. */
+ private boolean _persistent = false;
+
+ private Destination _consumerDestination;
+
+ /** Keeps track of the response destination of the previous message for the last reply to producer cache. */
+ private Destination _lastResponseDest;
+
+ /** The producer for sending replies with. */
+ private MessageProducer _replyProducer;
+
+ /** The consumer session. */
+ private Session _consumerSession;
+
+ /** The producer session. */
+ private Session _producerSession;
+
+ /** Holds the connection to the broker. */
+ private AMQConnection _connection;
+
+ /** Flag used to indicate if this is a point to point or pub/sub ping client. */
+ private boolean _isPubSub = false;
+
+ /**
+ * This flag is used to indicate that the user should be prompted to kill a broker, in order to test
+ * failover, immediately before committing a transaction.
+ */
+ protected boolean _failBeforeCommit = false;
+
+ /**
+ * This flag is used to indicate that the user should be prompted to a kill a broker, in order to test
+ * failover, immediate after committing a transaction.
+ */
+ protected boolean _failAfterCommit = false;
+
+ /**
+ * Creates a PingPongBouncer on the specified producer and consumer sessions.
+ *
+ * @param brokerDetails The addresses of the brokers to connect to.
+ * @param username The broker username.
+ * @param password The broker password.
+ * @param virtualpath The virtual host name within the broker.
+ * @param destinationName The name of the queue to receive pings on
+ * (or root of the queue name where many queues are generated).
+ * @param persistent A flag to indicate that persistent message should be used.
+ * @param transacted A flag to indicate that pings should be sent within transactions.
+ * @param selector A message selector to filter received pings with.
+ * @param verbose A flag to indicate that message timings should be sent to the console.
+ *
+ * @throws Exception All underlying exceptions allowed to fall through. This is only test code...
+ */
+ public PingPongBouncer(String brokerDetails, String username, String password, String virtualpath,
+ String destinationName, boolean persistent, boolean transacted, String selector, boolean verbose,
+ boolean pubsub) throws Exception
+ {
+ // Create a client id to uniquely identify this client.
+ InetAddress address = InetAddress.getLocalHost();
+ String clientId = address.getHostName() + System.currentTimeMillis();
+ _verbose = verbose;
+ _persistent = persistent;
+ setPubSub(pubsub);
+ // Connect to the broker.
+ setConnection(new AMQConnection(brokerDetails, username, password, clientId, virtualpath));
+ _logger.info("Connected with URL:" + getConnection().toURL());
+
+ // Set up the failover notifier.
+ getConnection().setConnectionListener(new FailoverNotifier());
+
+ // Create a session to listen for messages on and one to send replies on, transactional depending on the
+ // command line option.
+ _consumerSession = (Session) getConnection().createSession(transacted, Session.AUTO_ACKNOWLEDGE);
+ _producerSession = (Session) getConnection().createSession(transacted, Session.AUTO_ACKNOWLEDGE);
+
+ // Create the queue to listen for message on.
+ createConsumerDestination(destinationName);
+ MessageConsumer consumer =
+ _consumerSession.createConsumer(_consumerDestination, PREFETCH, NO_LOCAL, EXCLUSIVE, selector);
+
+ // Create a producer for the replies, without a default destination.
+ _replyProducer = _producerSession.createProducer(null);
+ _replyProducer.setDisableMessageTimestamp(true);
+ _replyProducer.setDeliveryMode(_persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT);
+
+ // Set this up to listen for messages on the queue.
+ consumer.setMessageListener(this);
+ }
+
+ /**
+ * Starts a stand alone ping-pong client running in verbose mode.
+ *
+ * @param args
+ */
+ public static void main(String[] args) throws Exception
+ {
+ System.out.println("Starting...");
+
+ // Display help on the command line.
+ if (args.length == 0)
+ {
+ _logger.info("Running test with default values...");
+ //usage();
+ //System.exit(0);
+ }
+
+ // Extract all command line parameters.
+ Config config = new Config();
+ config.setOptions(args);
+ String brokerDetails = config.getHost() + ":" + config.getPort();
+ String virtualpath = "/test";
+ String destinationName = config.getDestination();
+ if (destinationName == null)
+ {
+ destinationName = DEFAULT_DESTINATION_NAME;
+ }
+
+ String selector = config.getSelector();
+ boolean transacted = config.isTransacted();
+ boolean persistent = config.usePersistentMessages();
+ boolean pubsub = config.isPubSub();
+ boolean verbose = true;
+
+ //String selector = null;
+
+ // Instantiate the ping pong client with the command line options and start it running.
+ PingPongBouncer pingBouncer =
+ new PingPongBouncer(brokerDetails, "guest", "guest", virtualpath, destinationName, persistent, transacted,
+ selector, verbose, pubsub);
+ pingBouncer.getConnection().start();
+
+ System.out.println("Waiting...");
+ }
+
+ private static void usage()
+ {
+ System.err.println("Usage: PingPongBouncer \n" + "-host : broker host\n" + "-port : broker port\n"
+ + "-destinationname : queue/topic name\n" + "-transacted : (true/false). Default is false\n"
+ + "-persistent : (true/false). Default is false\n"
+ + "-pubsub : (true/false). Default is false\n" + "-selector : selector string\n");
+ }
+
+ /**
+ * This is a callback method that is notified of all messages for which this has been registered as a message
+ * listener on a message consumer. It sends a reply (pong) to all messages it receieves on the reply to
+ * destination of the message.
+ *
+ * @param message The message that triggered this callback.
+ */
+ public void onMessage(Message message)
+ {
+ try
+ {
+ String messageCorrelationId = message.getJMSCorrelationID();
+ if (_verbose)
+ {
+ _logger.info(timestampFormatter.format(new Date()) + ": Got ping with correlation id, "
+ + messageCorrelationId);
+ }
+
+ // Get the reply to destination from the message and check it is set.
+ Destination responseDest = message.getJMSReplyTo();
+
+ if (responseDest == null)
+ {
+ _logger.debug("Cannot send reply because reply-to destination is null.");
+
+ return;
+ }
+
+ // Spew out some timing information if verbose mode is on.
+ if (_verbose)
+ {
+ Long timestamp = message.getLongProperty("timestamp");
+
+ if (timestamp != null)
+ {
+ long diff = System.currentTimeMillis() - timestamp;
+ _logger.info("Time to bounce point: " + diff);
+ }
+ }
+
+ // Correlate the reply to the original.
+ message.setJMSCorrelationID(messageCorrelationId);
+
+ // Send the receieved message as the pong reply.
+ _replyProducer.send(responseDest, message);
+
+ if (_verbose)
+ {
+ _logger.info(timestampFormatter.format(new Date()) + ": Sent reply with correlation id, "
+ + messageCorrelationId);
+ }
+
+ // Commit the transaction if running in transactional mode.
+ commitTx(_producerSession);
+ }
+ catch (JMSException e)
+ {
+ _logger.debug("There was a JMSException: " + e.getMessage(), e);
+ }
+ }
+
+ /**
+ * Gets the underlying connection that this ping client is running on.
+ *
+ * @return The underlying connection that this ping client is running on.
+ */
+ public AMQConnection getConnection()
+ {
+ return _connection;
+ }
+
+ /**
+ * Sets the connection that this ping client is using.
+ *
+ * @param connection The ping connection.
+ */
+ public void setConnection(AMQConnection connection)
+ {
+ this._connection = connection;
+ }
+
+ /**
+ * Sets or clears the pub/sub flag to indiciate whether this client is pinging a queue or a topic.
+ *
+ * @param pubsub <tt>true</tt> if this client is pinging a topic, <tt>false</tt> if it is pinging a queue.
+ */
+ public void setPubSub(boolean pubsub)
+ {
+ _isPubSub = pubsub;
+ }
+
+ /**
+ * Checks whether this client is a p2p or pub/sub ping client.
+ *
+ * @return <tt>true</tt> if this client is pinging a topic, <tt>false</tt> if it is pinging a queue.
+ */
+ public boolean isPubSub()
+ {
+ return _isPubSub;
+ }
+
+ /**
+ * Convenience method to commit the transaction on the specified session. If the session to commit on is not
+ * a transactional session, this method does nothing.
+ *
+ * <p/>If the {@link #_failBeforeCommit} flag is set, this will prompt the user to kill the broker before the
+ * commit is applied. If the {@link #_failAfterCommit} flag is set, this will prompt the user to kill the broker
+ * after the commit is applied.
+ *
+ * @throws javax.jms.JMSException If the commit fails and then the rollback fails.
+ */
+ protected void commitTx(Session session) throws JMSException
+ {
+ if (session.getTransacted())
+ {
+ try
+ {
+ if (_failBeforeCommit)
+ {
+ _logger.trace("Failing Before Commit");
+ doFailover();
+ }
+
+ session.commit();
+
+ if (_failAfterCommit)
+ {
+ _logger.trace("Failing After Commit");
+ doFailover();
+ }
+
+ _logger.trace("Session Commited.");
+ }
+ catch (JMSException e)
+ {
+ _logger.trace("JMSException on commit:" + e.getMessage(), e);
+
+ try
+ {
+ session.rollback();
+ _logger.debug("Message rolled back.");
+ }
+ catch (JMSException jmse)
+ {
+ _logger.trace("JMSE on rollback:" + jmse.getMessage(), jmse);
+
+ // Both commit and rollback failed. Throw the rollback exception.
+ throw jmse;
+ }
+ }
+ }
+ }
+
+ /**
+ * Prompts the user to terminate the named broker, in order to test failover functionality. This method will block
+ * until the user supplied some input on the terminal.
+ *
+ * @param broker The name of the broker to terminate.
+ */
+ protected void doFailover(String broker)
+ {
+ System.out.println("Kill Broker " + broker + " now.");
+ try
+ {
+ System.in.read();
+ }
+ catch (IOException e)
+ { }
+
+ System.out.println("Continuing.");
+ }
+
+ /**
+ * Prompts the user to terminate the broker, in order to test failover functionality. This method will block
+ * until the user supplied some input on the terminal.
+ */
+ protected void doFailover()
+ {
+ System.out.println("Kill Broker now.");
+ try
+ {
+ System.in.read();
+ }
+ catch (IOException e)
+ { }
+
+ System.out.println("Continuing.");
+
+ }
+
+ private void createConsumerDestination(String name)
+ {
+ if (isPubSub())
+ {
+ _consumerDestination = new AMQTopic(name);
+ }
+ else
+ {
+ _consumerDestination = new AMQQueue(name);
+ }
+ }
+
+ /**
+ * A connection listener that logs out any failover complete events. Could do more interesting things with this
+ * at some point...
+ */
+ public static class FailoverNotifier implements ConnectionListener
+ {
+ public void bytesSent(long count)
+ { }
+
+ public void bytesReceived(long count)
+ { }
+
+ public boolean preFailover(boolean redirect)
+ {
+ return true;
+ }
+
+ public boolean preResubscribe()
+ {
+ return true;
+ }
+
+ public void failoverComplete()
+ {
+ _logger.info("App got failover complete callback.");
+ }
+ }
+}
diff --git a/java/perftests/src/main/java/org/apache/qpid/requestreply/PingPongProducer.java b/java/perftests/src/main/java/org/apache/qpid/requestreply/PingPongProducer.java
new file mode 100644
index 0000000000..885277c533
--- /dev/null
+++ b/java/perftests/src/main/java/org/apache/qpid/requestreply/PingPongProducer.java
@@ -0,0 +1,1127 @@
+/*
+ *
+ * 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.requestreply;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.*;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
+
+import javax.jms.*;
+
+import org.apache.log4j.Logger;
+
+import org.apache.qpid.client.*;
+import org.apache.qpid.client.message.TestMessageFactory;
+import org.apache.qpid.framing.AMQShortString;
+import org.apache.qpid.jms.MessageProducer;
+import org.apache.qpid.jms.Session;
+import org.apache.qpid.topic.Config;
+
+import uk.co.thebadgerset.junit.extensions.BatchedThrottle;
+import uk.co.thebadgerset.junit.extensions.Throttle;
+
+/**
+ * PingPongProducer is a client that sends pings to a queue and waits for pongs to be bounced back by a bounce back
+ * client (see {@link PingPongBouncer} for the bounce back client).
+ *
+ * <p/>The pings are sent with a reply-to field set to a single temporary queue, which is the same for all pings.
+ * This means that this class has to do some work to correlate pings with pongs; it expectes the original message
+ * correlation id in the ping to be bounced back in the reply correlation id.
+ *
+ * <p/>This ping tool accepts a vast number of configuration options, all of which are passed in to the constructor.
+ * It can ping topics or queues; ping multiple destinations; do persistent pings; send messages of any size; do pings
+ * within transactions; control the number of pings to send in each transaction; limit its sending rate; and perform
+ * failover testing.
+ *
+ * <p/>This implements the Runnable interface with a run method that implements an infinite ping loop. The ping loop
+ * does all its work through helper methods, so that code wishing to run a ping-pong cycle is not forced to do so
+ * by starting a new thread. The command line invocation does take advantage of this ping loop. A shutdown hook is
+ * also registered to terminate the ping-pong loop cleanly.
+ *
+ * <p/><table id="crc"><caption>CRC Card</caption>
+ * <tr><th> Responsibilities <th> Collaborations
+ * <tr><td> Provide a ping and wait for all responses cycle.
+ * <tr><td> Provide command line invocation to loop the ping cycle on a configurable broker url.
+ * </table>
+ *
+ * @todo The use of a ping rate {@link #DEFAULT_RATE} and waits between pings {@link #DEFAULT_SLEEP_TIME} are overlapping.
+ * Use the rate and throttling only.
+ *
+ * @todo Make shared or unique destinations a configurable option, hard coded to false.
+ */
+public class PingPongProducer implements Runnable, MessageListener, ExceptionListener
+{
+ private static final Logger _logger = Logger.getLogger(PingPongProducer.class);
+
+ /** Holds the name of the property to get the test message size from. */
+ public static final String MESSAGE_SIZE_PROPNAME = "messagesize";
+
+ /** Holds the name of the property to get the ping queue name from. */
+ public static final String PING_QUEUE_NAME_PROPNAME = "destinationname";
+
+ /** Holds the name of the property to get the test delivery mode from. */
+ public static final String PERSISTENT_MODE_PROPNAME = "persistent";
+
+ /** Holds the name of the property to get the test transactional mode from. */
+ public static final String TRANSACTED_PROPNAME = "transacted";
+
+ /** Holds the name of the property to get the test broker url from. */
+ public static final String BROKER_PROPNAME = "broker";
+
+ /** Holds the name of the property to get the test broker virtual path. */
+ public static final String VIRTUAL_PATH_PROPNAME = "virtualPath";
+
+ /** Holds the name of the property to get the message rate from. */
+ public static final String RATE_PROPNAME = "rate";
+
+ public static final String VERBOSE_OUTPUT_PROPNAME = "verbose";
+
+ /** Holds the true or false depending on wether it is P2P test or PubSub */
+ public static final String IS_PUBSUB_PROPNAME = "pubsub";
+
+ public static final String FAIL_AFTER_COMMIT_PROPNAME = "FailAfterCommit";
+
+ public static final String FAIL_BEFORE_COMMIT_PROPNAME = "FailBeforeCommit";
+
+ public static final String FAIL_AFTER_SEND_PROPNAME = "FailAfterSend";
+
+ public static final String FAIL_BEFORE_SEND_PROPNAME = "FailBeforeSend";
+
+ public static final String FAIL_ONCE_PROPNAME = "FailOnce";
+
+ public static final String USERNAME_PROPNAME = "username";
+
+ public static final String PASSWORD_PROPNAME = "password";
+
+ public static final String SELECTOR_PROPNAME = "selector";
+
+ public static final String PING_DESTINATION_COUNT_PROPNAME = "destinationscount";
+
+ /** Holds the name of the property to get the waiting timeout for response messages. */
+ public static final String TIMEOUT_PROPNAME = "timeout";
+
+ public static final String COMMIT_BATCH_SIZE_PROPNAME = "CommitBatchSize";
+
+ /** Used to set up a default message size. */
+ public static final int DEFAULT_MESSAGE_SIZE = 0;
+
+ /** Holds the name of the default destination to send pings on. */
+ public static final String DEFAULT_PING_DESTINATION_NAME = "ping";
+
+ /** Defines the default number of destinations to ping. */
+ public static final int DEFAULT_DESTINATION_COUNT = 1;
+
+ /** Defines the default rate (in pings per second) to send pings at. 0 means as fast as possible, no restriction. */
+ public static final int DEFAULT_RATE = 0;
+
+ /** Defines the default wait between pings. */
+ public static final long DEFAULT_SLEEP_TIME = 250;
+
+ /** Default time to wait before assuming that a ping has timed out. */
+ public static final long DEFAULT_TIMEOUT = 9000;
+
+ /** Defines the default number of pings to send in each transaction when running transactionally. */
+ public static final int DEFAULT_TX_BATCH_SIZE = 100;
+
+ /** Defines the default prefetch size to use when consuming messages. */
+ public static final int DEFAULT_PREFETCH = 100;
+
+ /** Defines the default value of the no local flag to use when consuming messages. */
+ public static final boolean DEFAULT_NO_LOCAL = false;
+
+ /** Defines the default value of the exclusive flag to use when consuming messages. */
+ public static final boolean DEFAULT_EXCLUSIVE = false;
+
+ /** Holds the message delivery mode to use for the test. */
+ public static final boolean DEFAULT_PERSISTENT_MODE = false;
+
+ /** Holds the transactional mode to use for the test. */
+ public static final boolean DEFAULT_TRANSACTED = false;
+
+ /** Holds the default broker url for the test. */
+ public static final String DEFAULT_BROKER = "tcp://localhost:5672";
+
+ /** Holds the default virtual path for the test. */
+ public static final String DEFAULT_VIRTUAL_PATH = "test";
+
+ /** Holds the pub/sub mode default, true means ping a topic, false means ping a queue. */
+ public static final boolean DEFAULT_PUBSUB = false;
+
+ /** Holds the default broker log on username. */
+ public static final String DEFAULT_USERNAME = "guest";
+
+ /** Holds the default broker log on password. */
+ public static final String DEFAULT_PASSWORD = "guest";
+
+ /** Holds the default message selector. */
+ public static final String DEFAULT_SELECTOR = null;
+
+ /** Holds the default failover after commit test flag. */
+ public static final String DEFAULT_FAIL_AFTER_COMMIT = "false";
+
+ /** Holds the default failover before commit test flag. */
+ public static final String DEFAULT_FAIL_BEFORE_COMMIT = "false";
+
+ /** Holds the default failover after send test flag. */
+ public static final String DEFAULT_FAIL_AFTER_SEND = "false";
+
+ /** Holds the default failover before send test flag. */
+ public static final String DEFAULT_FAIL_BEFORE_SEND = "false";
+
+ /** Holds the default failover only once flag, true means only do one failover, false means failover on every commit cycle. */
+ public static final String DEFAULT_FAIL_ONCE = "true";
+
+ /** Holds the default verbose mode. */
+ public static final boolean DEFAULT_VERBOSE = false;
+
+ /** Holds the name of the property to store nanosecond timestamps in ping messages with. */
+ public static final String MESSAGE_TIMESTAMP_PROPNAME = "timestamp";
+
+ /** A source for providing sequential unique correlation ids. These will be unique within the same JVM. */
+ private static AtomicLong idGenerator = new AtomicLong(0L);
+
+ /**
+ * Holds a map from message ids to latches on which threads wait for replies. This map is shared accross
+ * multiple ping producers on the same JVM.
+ */
+ private static Map<String, CountDownLatch> trafficLights =
+ Collections.synchronizedMap(new HashMap<String, CountDownLatch>());
+
+ /** A convenient formatter to use when time stamping output. */
+ protected static final DateFormat timestampFormatter = new SimpleDateFormat("hh:mm:ss:SS");
+
+ /**
+ * This id generator is used to generate ids to append to the queue name to ensure that queues can be unique when
+ * creating multiple ping producers in the same JVM.
+ */
+ protected static AtomicInteger _queueJVMSequenceID = new AtomicInteger();
+
+ /** Destination where the response messages will arrive. */
+ private Destination _replyDestination;
+
+ /** Destination where the producer will be sending message to. */
+ //private Destination _pingDestination;
+
+ /** Determines whether this producer sends persistent messages. */
+ protected boolean _persistent;
+
+ /** Determines what size of messages this producer sends. */
+ protected int _messageSize;
+
+ /** Used to indicate that the ping loop should print out whenever it pings. */
+ protected boolean _verbose = false;
+
+ /** Holds the session on which ping replies are received. */
+ protected Session _consumerSession;
+
+ /** Used to restrict the sending rate to a specified limit. */
+ private Throttle _rateLimiter = null;
+
+ /** Holds a message listener that this message listener chains all its messages to. */
+ private ChainedMessageListener _chainedMessageListener = null;
+
+ /** Flag used to indicate if this is a point to point or pub/sub ping client. */
+ protected boolean _isPubSub = false;
+
+ /**
+ * This id generator is used to generates ids that are only unique within this pinger. Creating multiple pingers
+ * on the same JVM using this id generator will allow them to ping on the same queues.
+ */
+ protected AtomicInteger _queueSharedId = new AtomicInteger();
+
+ /** Used to tell the ping loop when to terminate, it only runs while this is true. */
+ protected boolean _publish = true;
+
+ /** Holds the connection to the broker. */
+ private Connection _connection;
+
+ /** Holds the producer session, needed to create ping messages. */
+ private Session _producerSession;
+
+ /** Holds the set of destiniations that this ping producer pings. */
+ protected List<Destination> _pingDestinations = new ArrayList<Destination>();
+
+ /** Holds the message producer to send the pings through. */
+ protected MessageProducer _producer;
+
+ /** Flag used to indicate that the user should be prompted to terminate a broker, to test failover before a commit. */
+ protected boolean _failBeforeCommit = false;
+
+ /** Flag used to indicate that the user should be prompted to terminate a broker, to test failover after a commit. */
+ protected boolean _failAfterCommit = false;
+
+ /** Flag used to indicate that the user should be prompted to terminate a broker, to test failover before a send. */
+ protected boolean _failBeforeSend = false;
+
+ /** Flag used to indicate that the user should be prompted to terminate a broker, to test failover after a send. */
+ protected boolean _failAfterSend = false;
+
+ /** Flag used to indicate that failover prompting should only be done on the first commit, not on every commit. */
+ protected boolean _failOnce = true;
+
+ /** Holds the number of sends that should be performed in every transaction when using transactions. */
+ protected int _txBatchSize = 1;
+
+ /**
+ * Creates a ping producer with the specified parameters, of which there are many. See their individual comments
+ * for details. This constructor creates a connection to the broker and creates producer and consumer sessions on it,
+ * to send and recieve its pings and replies on. The other options are kept, and control how this pinger behaves.
+ *
+ * @param brokerDetails The URL of the broker to send pings to.
+ * @param username The username to log onto the broker with.
+ * @param password The password to log onto the broker with.
+ * @param virtualpath The virtual host name to use on the broker.
+ * @param destinationName The name (or root where multiple destinations are used) of the desitination to send
+ * pings to.
+ * @param selector The selector to filter replies with.
+ * @param transacted Indicates whether or not pings are sent and received in transactions.
+ * @param persistent Indicates whether pings are sent using peristent delivery.
+ * @param messageSize Specifies the size of ping messages to send.
+ * @param verbose Indicates that information should be printed to the console on every ping.
+ * @param afterCommit Indicates that the user should be promted to terminate a broker after commits to test failover.
+ * @param beforeCommit Indicates that the user should be promted to terminate a broker before commits to test failover.
+ * @param afterSend Indicates that the user should be promted to terminate a broker after sends to test failover.
+ * @param beforeSend Indicates that the user should be promted to terminate a broker before sends to test failover.
+ * @param failOnce Indicates that the failover testing behaviour should only happen on the first commit, not all.
+ * @param txBatchSize Specifies the number of pings to send in each transaction.
+ * @param noOfDestinations The number of destinations to ping. Must be 1 or more.
+ * @param rate Specified the number of pings per second to send. Setting this to 0 means send as fast as
+ * possible, with no rate restriction.
+ * @param pubsub
+ *
+ * @throws Exception Any exceptions are allowed to fall through.
+ */
+ public PingPongProducer(String brokerDetails, String username, String password, String virtualpath,
+ String destinationName, String selector, boolean transacted, boolean persistent, int messageSize,
+ boolean verbose, boolean afterCommit, boolean beforeCommit, boolean afterSend,
+ boolean beforeSend, boolean failOnce, int txBatchSize, int noOfDestinations, int rate,
+ boolean pubsub) throws Exception
+ {
+ // Check that one or more destinations were specified.
+ if (noOfDestinations < 1)
+ {
+ throw new IllegalArgumentException("There must be at least one destination.");
+ }
+
+ // Create a connection to the broker.
+ InetAddress address = InetAddress.getLocalHost();
+ String clientID = address.getHostName() + System.currentTimeMillis();
+
+ _connection = new AMQConnection(brokerDetails, username, password, clientID, virtualpath);
+
+ // Create transactional or non-transactional sessions, based on the command line arguments.
+ _producerSession = (Session) getConnection().createSession(transacted, Session.AUTO_ACKNOWLEDGE);
+ _consumerSession = (Session) getConnection().createSession(transacted, Session.AUTO_ACKNOWLEDGE);
+
+ // Set up a throttle to control the send rate, if a rate > 0 is specified.
+ if (rate > 0)
+ {
+ _rateLimiter = new BatchedThrottle();
+ _rateLimiter.setRate(rate);
+ }
+
+ // Create the temporary queue for replies.
+ _replyDestination = _consumerSession.createTemporaryQueue();
+
+ // Create the producer and the consumers for all reply destinations.
+ createProducer();
+ createPingDestinations(noOfDestinations, selector, destinationName, true);
+ createReplyConsumers(getReplyDestinations(), selector);
+
+ // Keep all the remaining options.
+ _persistent = persistent;
+ _messageSize = messageSize;
+ _verbose = verbose;
+ _failAfterCommit = afterCommit;
+ _failBeforeCommit = beforeCommit;
+ _failAfterSend = afterSend;
+ _failBeforeSend = beforeSend;
+ _failOnce = failOnce;
+ _txBatchSize = txBatchSize;
+ _isPubSub = pubsub;
+ }
+
+ /**
+ * Starts a ping-pong loop running from the command line. The bounce back client {@link PingPongBouncer} also needs
+ * to be started to bounce the pings back again.
+ *
+ * @param args The command line arguments.
+ */
+ public static void main(String[] args) throws Exception
+ {
+ // Extract the command line.
+ Config config = new Config();
+ config.setOptions(args);
+ if (args.length == 0)
+ {
+ _logger.info("Running test with default values...");
+ //usage();
+ //System.exit(0);
+ }
+
+ String brokerDetails = config.getHost() + ":" + config.getPort();
+ String virtualpath = "/test";
+ String selector = (config.getSelector() == null) ? DEFAULT_SELECTOR : config.getSelector();
+ boolean verbose = true;
+ boolean transacted = config.isTransacted();
+ boolean persistent = config.usePersistentMessages();
+ int messageSize = (config.getPayload() != 0) ? config.getPayload() : DEFAULT_MESSAGE_SIZE;
+ //int messageCount = config.getMessages();
+ int destCount = (config.getDestinationsCount() != 0) ? config.getDestinationsCount() : DEFAULT_DESTINATION_COUNT;
+ int batchSize = (config.getBatchSize() != 0) ? config.getBatchSize() : DEFAULT_TX_BATCH_SIZE;
+ int rate = (config.getRate() != 0) ? config.getRate() : DEFAULT_RATE;
+ boolean pubsub = config.isPubSub();
+
+ String destName = config.getDestination();
+ if (destName == null)
+ {
+ destName = DEFAULT_PING_DESTINATION_NAME;
+ }
+
+ boolean afterCommit = false;
+ boolean beforeCommit = false;
+ boolean afterSend = false;
+ boolean beforeSend = false;
+ boolean failOnce = false;
+
+ for (String arg : args)
+ {
+ if (arg.startsWith("failover:"))
+ {
+ //failover:<before|after>:<send:commit> | failover:once
+ String[] parts = arg.split(":");
+ if (parts.length == 3)
+ {
+ if (parts[2].equals("commit"))
+ {
+ afterCommit = parts[1].equals("after");
+ beforeCommit = parts[1].equals("before");
+ }
+
+ if (parts[2].equals("send"))
+ {
+ afterSend = parts[1].equals("after");
+ beforeSend = parts[1].equals("before");
+ }
+
+ if (parts[1].equals("once"))
+ {
+ failOnce = true;
+ }
+ }
+ else
+ {
+ System.out.println("Unrecognized failover request:" + arg);
+ }
+ }
+ }
+
+ // Create a ping producer to handle the request/wait/reply cycle.
+ PingPongProducer pingProducer =
+ new PingPongProducer(brokerDetails, DEFAULT_USERNAME, DEFAULT_PASSWORD, virtualpath, destName, selector,
+ transacted, persistent, messageSize, verbose, afterCommit, beforeCommit, afterSend,
+ beforeSend, failOnce, batchSize, destCount, rate, pubsub);
+
+ pingProducer.getConnection().start();
+
+ // Create a shutdown hook to terminate the ping-pong producer.
+ Runtime.getRuntime().addShutdownHook(pingProducer.getShutdownHook());
+
+ // Ensure that the ping pong producer is registered to listen for exceptions on the connection too.
+ pingProducer.getConnection().setExceptionListener(pingProducer);
+
+ // Create the ping loop thread and run it until it is terminated by the shutdown hook or exception.
+ Thread pingThread = new Thread(pingProducer);
+ pingThread.run();
+ pingThread.join();
+ }
+
+ /**
+ * Convenience method for a short pause.
+ *
+ * @param sleepTime The time in milliseconds to pause for.
+ */
+ public static void pause(long sleepTime)
+ {
+ if (sleepTime > 0)
+ {
+ try
+ {
+ Thread.sleep(sleepTime);
+ }
+ catch (InterruptedException ie)
+ { }
+ }
+ }
+
+ /**
+ * Gets all the reply destinations (to listen for replies on). In this case this will just be the single reply
+ * to destination of this pinger.
+ *
+ * @return The single reply to destination of this pinger, wrapped in a list.
+ */
+ public List<Destination> getReplyDestinations()
+ {
+ _logger.debug("public List<Destination> getReplyDestinations(): called");
+
+ List<Destination> replyDestinations = new ArrayList<Destination>();
+ replyDestinations.add(_replyDestination);
+
+ return replyDestinations;
+ }
+
+ /**
+ * Creates the producer to send the pings on. This is created without a default destination. Its persistent delivery
+ * flag is set accoring the ping producer creation options.
+ *
+ * @throws JMSException Any JMSExceptions are allowed to fall through.
+ */
+ public void createProducer() throws JMSException
+ {
+ _logger.debug("public void createProducer(): called");
+
+ _producer = (MessageProducer) _producerSession.createProducer(null);
+ //_producer.setDisableMessageTimestamp(true);
+ _producer.setDeliveryMode(_persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT);
+ }
+
+ /**
+ * Creates consumers for the specified number of destinations. The destinations themselves are also created by
+ * this method.
+ *
+ * @param noOfDestinations The number of destinations to create consumers for.
+ * @param selector The message selector to filter the consumers with.
+ * @param rootName The root of the name, or actual name if only one is being created.
+ * @param unique <tt>true</tt> to make the destinations unique to this pinger, <tt>false</tt> to share
+ * the numbering with all pingers on the same JVM.
+ *
+ * @throws JMSException Any JMSExceptions are allowed to fall through.
+ */
+ public void createPingDestinations(int noOfDestinations, String selector, String rootName, boolean unique)
+ throws JMSException
+ {
+ _logger.debug("public void createPingDestinations(int noOfDestinations = " + noOfDestinations
+ + ", String selector = " + selector + ", String rootName = " + rootName + ", boolean unique = "
+ + unique + "): called");
+
+ // Create the desired number of ping destinations and consumers for them.
+ for (int i = 0; i < noOfDestinations; i++)
+ {
+ AMQDestination destination = null;
+
+ int id;
+
+ // Generate an id, unique within this pinger or to the whole JVM depending on the unique flag.
+ if (unique)
+ {
+ id = _queueJVMSequenceID.incrementAndGet();
+ }
+ else
+ {
+ id = _queueSharedId.incrementAndGet();
+ }
+
+ // Check if this is a pub/sub pinger, in which case create topics.
+ if (_isPubSub)
+ {
+ AMQShortString name = new AMQShortString(rootName + id);
+ destination = new AMQTopic(name);
+ }
+ // Otherwise this is a p2p pinger, in which case create queues.
+ else
+ {
+ AMQShortString name = new AMQShortString(rootName + id);
+ destination = new AMQQueue(name, name, false, false, false);
+ }
+
+ // Keep the destination.
+ _pingDestinations.add(destination);
+ }
+ }
+
+ /**
+ * Stores the received message in the replies map, then resets the boolean latch that a thread waiting for a
+ * correlating reply may be waiting on. This is only done if the reply has a correlation id that is expected
+ * in the replies map.
+ *
+ * @param message The received message.
+ */
+ public void onMessage(Message message)
+ {
+ _logger.debug("public void onMessage(Message message): called");
+
+ try
+ {
+ // Extract the messages correlation id.
+ String correlationID = message.getJMSCorrelationID();
+ _logger.debug("correlationID = " + correlationID);
+
+ // Countdown on the traffic light if there is one for the matching correlation id.
+ CountDownLatch trafficLight = trafficLights.get(correlationID);
+
+ if (trafficLight != null)
+ {
+ _logger.debug("Reply was expected, decrementing the latch for the id, " + correlationID);
+
+ // Decrement the countdown latch. Before this point, it is possible that two threads might enter this
+ // method simultanesouly with the same correlation id. Decrementing the latch in a synchronized block
+ // ensures that each thread will get a unique value for the remaining messages.
+ long trueCount = -1;
+ long remainingCount = -1;
+
+ synchronized (trafficLight)
+ {
+ trafficLight.countDown();
+
+ trueCount = trafficLight.getCount();
+ remainingCount = trueCount - 1;
+
+ _logger.debug("remainingCount = " + remainingCount);
+ _logger.debug("trueCount = " + trueCount);
+
+ // Commit on transaction batch size boundaries. At this point in time the waiting producer remains
+ // blocked, even on the last message.
+ if ((remainingCount % _txBatchSize) == 0)
+ {
+ commitTx(_consumerSession);
+ }
+
+ // Forward the message and remaining count to any interested chained message listener.
+ if (_chainedMessageListener != null)
+ {
+ _chainedMessageListener.onMessage(message, (int) remainingCount);
+ }
+
+ // Check if this is the last message, in which case release any waiting producers. This is done
+ // after the transaction has been committed and any listeners notified.
+ if (trueCount == 1)
+ {
+ trafficLight.countDown();
+ }
+ }
+ }
+ else
+ {
+ _logger.debug("There was no thread waiting for reply: " + correlationID);
+ }
+
+ // Print out ping times for every message in verbose mode only.
+ if (_verbose)
+ {
+ Long timestamp = message.getLongProperty(MESSAGE_TIMESTAMP_PROPNAME);
+
+ if (timestamp != null)
+ {
+ long diff = System.nanoTime() - timestamp;
+ _logger.trace("Time for round trip (nanos): " + diff);
+ }
+ }
+ }
+ catch (JMSException e)
+ {
+ _logger.warn("There was a JMSException: " + e.getMessage(), e);
+ }
+
+ _logger.debug("public void onMessage(Message message): ending");
+ }
+
+ /**
+ * Sends the specified number of ping message and then waits for all correlating replies. If the wait times out
+ * before a reply arrives, then a null reply is returned from this method. This method generates a new unqiue
+ * correlation id for the messages.
+ *
+ * @param message The message to send.
+ * @param numPings The number of ping messages to send.
+ * @param timeout The timeout in milliseconds.
+ *
+ * @return The number of replies received. This may be less than the number sent if the timeout terminated the
+ * wait for all prematurely.
+ *
+ * @throws JMSException All underlying JMSExceptions are allowed to fall through.
+ */
+ public int pingAndWaitForReply(Message message, int numPings, long timeout) throws JMSException, InterruptedException
+ {
+ _logger.debug("public int pingAndWaitForReply(Message message, int numPings = " + numPings + ", long timeout = "
+ + timeout + "): called");
+
+ // Create a unique correlation id to put on the messages before sending them.
+ String messageCorrelationId = Long.toString(idGenerator.incrementAndGet());
+
+ return pingAndWaitForReply(message, numPings, timeout, messageCorrelationId);
+ }
+
+ /**
+ * Sends the specified number of ping message and then waits for all correlating replies. If the wait times out
+ * before a reply arrives, then a null reply is returned from this method. This method allows the caller to specify
+ * the correlation id.
+ *
+ * @param message The message to send.
+ * @param numPings The number of ping messages to send.
+ * @param timeout The timeout in milliseconds.
+ * @param messageCorrelationId The message correlation id.
+ *
+ * @return The number of replies received. This may be less than the number sent if the timeout terminated the
+ * wait for all prematurely.
+ *
+ * @throws JMSException All underlying JMSExceptions are allowed to fall through.
+ */
+ public int pingAndWaitForReply(Message message, int numPings, long timeout, String messageCorrelationId)
+ throws JMSException, InterruptedException
+ {
+ _logger.debug("public int pingAndWaitForReply(Message message, int numPings = " + numPings + ", long timeout = "
+ + timeout + ", String messageCorrelationId = " + messageCorrelationId + "): called");
+
+ try
+ {
+ // Create a count down latch to count the number of replies with. This is created before the messages are
+ // sent so that the replies cannot be received before the count down is created.
+ // One is added to this, so that the last reply becomes a special case. The special case is that the
+ // chained message listener must be called before this sender can be unblocked, but that decrementing the
+ // countdown needs to be done before the chained listener can be called.
+ CountDownLatch trafficLight = new CountDownLatch(numPings + 1);
+ trafficLights.put(messageCorrelationId, trafficLight);
+
+ // Send the specifed number of messages.
+ pingNoWaitForReply(message, numPings, messageCorrelationId);
+
+ // Block the current thread until replies to all the message are received, or it times out.
+ trafficLight.await(timeout, TimeUnit.MILLISECONDS);
+
+ // Work out how many replies were receieved.
+ int numReplies = numPings - (int) trafficLight.getCount();
+
+ if ((numReplies < numPings) && _verbose)
+ {
+ _logger.info("Timed out (" + timeout + " ms) before all replies received on id, " + messageCorrelationId);
+ }
+ else if (_verbose)
+ {
+ _logger.info("Got all replies on id, " + messageCorrelationId);
+ }
+
+ commitTx(_consumerSession);
+
+ _logger.debug("public int pingAndWaitForReply(Message message, int numPings, long timeout): ending");
+
+ return numReplies;
+ }
+ // Ensure that the message countdown latch is always removed from the reply map. The reply map is long lived,
+ // so will be a memory leak if this is not done.
+ finally
+ {
+ trafficLights.remove(messageCorrelationId);
+ }
+ }
+
+ /**
+ * Sends the specified number of ping messages and does not wait for correlating replies.
+ *
+ * @param message The message to send.
+ * @param numPings The number of pings to send.
+ * @param messageCorrelationId A correlation id to place on all messages sent.
+ *
+ * @throws JMSException All underlying JMSExceptions are allowed to fall through.
+ */
+ public void pingNoWaitForReply(Message message, int numPings, String messageCorrelationId) throws JMSException
+ {
+ _logger.debug("public void pingNoWaitForReply(Message message, int numPings = " + numPings
+ + ", String messageCorrelationId = " + messageCorrelationId + "): called");
+
+ message.setJMSCorrelationID(messageCorrelationId);
+
+ // Set up a committed flag to detect uncommitted messages at the end of the send loop. This may occurr if the
+ // transaction batch size is not a factor of the number of pings. In which case an extra commit at the end is
+ // needed.
+ boolean committed = false;
+
+ // Send all of the ping messages.
+ for (int i = 0; i < numPings; i++)
+ {
+ // Reset the committed flag to indicate that there are uncommitted messages.
+ committed = false;
+
+ // Re-timestamp the message.
+ message.setLongProperty(MESSAGE_TIMESTAMP_PROPNAME, System.nanoTime());
+
+ // Round robin the destinations as the messages are sent.
+ //return _destinationCount;
+ sendMessage(_pingDestinations.get(i % _pingDestinations.size()), message);
+
+ // Apply message rate throttling if a rate limit has been set up.
+ if (_rateLimiter != null)
+ {
+ _rateLimiter.throttle();
+ }
+
+ // Call commit every time the commit batch size is reached.
+ if ((i % _txBatchSize) == 0)
+ {
+ commitTx(_producerSession);
+ committed = true;
+ }
+
+ // Spew out per message timings on every message sonly in verbose mode.
+ if (_verbose)
+ {
+ _logger.info(timestampFormatter.format(new Date()) + ": Pinged at with correlation id, "
+ + messageCorrelationId);
+ }
+ }
+
+ // Call commit if the send loop finished before reaching a batch size boundary so there may still be uncommitted messages.
+ if (!committed)
+ {
+ commitTx(_producerSession);
+ }
+ }
+
+ /**
+ * The ping loop implementation. This sends out pings waits for replies and inserts short pauses in between each.
+ */
+ public void pingLoop()
+ {
+ try
+ {
+ // Generate a sample message and time stamp it.
+ ObjectMessage msg = getTestMessage(_replyDestination, _messageSize, _persistent);
+ msg.setLongProperty(MESSAGE_TIMESTAMP_PROPNAME, System.nanoTime());
+
+ // Send the message and wait for a reply.
+ pingAndWaitForReply(msg, DEFAULT_TX_BATCH_SIZE, DEFAULT_TIMEOUT);
+
+ // Introduce a short pause if desired.
+ pause(DEFAULT_SLEEP_TIME);
+ }
+ catch (JMSException e)
+ {
+ _publish = false;
+ _logger.debug("There was a JMSException: " + e.getMessage(), e);
+ }
+ catch (InterruptedException e)
+ {
+ _publish = false;
+ _logger.debug("There was an interruption: " + e.getMessage(), e);
+ }
+ }
+
+ /*public Destination getReplyDestination()
+ {
+ return _replyDestination;
+ }*/
+
+ /**
+ * Sets a chained message listener. The message listener on this pinger, chains all its messages to the one set
+ * here.
+ *
+ * @param messageListener The chained message listener.
+ */
+ public void setChainedMessageListener(ChainedMessageListener messageListener)
+ {
+ _chainedMessageListener = messageListener;
+ }
+
+ /**
+ * Removes any chained message listeners from this pinger.
+ */
+ public void removeChainedMessageListener()
+ {
+ _chainedMessageListener = null;
+ }
+
+ /**
+ * Generates a test message of the specified size, with the specified reply-to destination and persistence flag.
+ *
+ * @param replyQueue The reply-to destination for the message.
+ * @param messageSize The desired size of the message in bytes.
+ * @param persistent <tt>true</tt> if the message should use persistent delivery, <tt>false</tt> otherwise.
+ *
+ * @return A freshly generated test message.
+ *
+ * @throws javax.jms.JMSException All underlying JMSException are allowed to fall through.
+ */
+ public ObjectMessage getTestMessage(Destination replyQueue, int messageSize, boolean persistent) throws JMSException
+ {
+ ObjectMessage msg = TestMessageFactory.newObjectMessage(_producerSession, replyQueue, messageSize, persistent);
+
+ // Timestamp the message in nanoseconds.
+ msg.setLongProperty(MESSAGE_TIMESTAMP_PROPNAME, System.nanoTime());
+
+ return msg;
+ }
+
+ /**
+ * Stops the ping loop by clearing the publish flag. The current loop will complete before it notices that this
+ * flag has been cleared.
+ */
+ public void stop()
+ {
+ _publish = false;
+ }
+
+ /**
+ * Implements a ping loop that repeatedly pings until the publish flag becomes false.
+ */
+ public void run()
+ {
+ // Keep running until the publish flag is cleared.
+ while (_publish)
+ {
+ pingLoop();
+ }
+ }
+
+ /**
+ * Callback method, implementing ExceptionListener. This should be registered to listen for exceptions on the
+ * connection, this clears the publish flag which in turn will halt the ping loop.
+ *
+ * @param e The exception that triggered this callback method.
+ */
+ public void onException(JMSException e)
+ {
+ _publish = false;
+ _logger.debug("There was a JMSException: " + e.getMessage(), e);
+ }
+
+ /**
+ * Gets a shutdown hook that will cleanly shut this down when it is running the ping loop. This can be registered
+ * with the runtime system as a shutdown hook.
+ *
+ * @return A shutdown hook for the ping loop.
+ */
+ public Thread getShutdownHook()
+ {
+ return new Thread(new Runnable()
+ {
+ public void run()
+ {
+ stop();
+ }
+ });
+ }
+
+ /**
+ * Gets the underlying connection that this ping client is running on.
+ *
+ * @return The underlying connection that this ping client is running on.
+ */
+ public Connection getConnection()
+ {
+ return _connection;
+ }
+
+ /**
+ * Creates consumers for the specified destinations and registers this pinger to listen to their messages.
+ *
+ * @param destinations The destinations to listen to.
+ * @param selector A selector to filter the messages with.
+ *
+ * @throws javax.jms.JMSException Any JMSExceptions are allowed to fall through.
+ */
+ public void createReplyConsumers(Collection<Destination> destinations, String selector) throws JMSException
+ {
+ _logger.debug("public void createReplyConsumers(Collection<Destination> destinations = " + destinations
+ + ", String selector = " + selector + "): called");
+
+ for (Destination destination : destinations)
+ {
+ // Create a consumer for the destination and set this pinger to listen to its messages.
+ MessageConsumer consumer =
+ _consumerSession.createConsumer(destination, DEFAULT_PREFETCH, DEFAULT_NO_LOCAL, DEFAULT_EXCLUSIVE,
+ selector);
+ consumer.setMessageListener(this);
+ }
+ }
+
+ /**
+ * Closes the pingers connection.
+ *
+ * @throws JMSException All JMSException are allowed to fall through.
+ */
+ public void close() throws JMSException
+ {
+ _logger.debug("public void close(): called");
+
+ if (_connection != null)
+ {
+ _connection.close();
+ }
+ }
+
+ /**
+ * Convenience method to commit the transaction on the specified session. If the session to commit on is not
+ * a transactional session, this method does nothing (unless the failover after send flag is set).
+ *
+ * <p/>If the {@link #_failAfterSend} flag is set, this will prompt the user to kill the broker before the commit
+ * is applied. This flag applies whether the pinger is transactional or not.
+ *
+ * <p/>If the {@link #_failBeforeCommit} flag is set, this will prompt the user to kill the broker before the
+ * commit is applied. If the {@link #_failAfterCommit} flag is set, this will prompt the user to kill the broker
+ * after the commit is applied. These flags will only apply if using a transactional pinger.
+ *
+ * @throws javax.jms.JMSException If the commit fails and then the rollback fails.
+ *
+ * @todo Consider moving the fail after send logic into the send method. It is confusing to have it in this commit
+ * method, because commits only apply to transactional pingers, but fail after send applied to transactional
+ * and non-transactional alike.
+ */
+ protected void commitTx(Session session) throws JMSException
+ {
+ _logger.debug("protected void commitTx(Session session): called");
+
+ _logger.trace("Batch time reached");
+ if (_failAfterSend)
+ {
+ _logger.trace("Batch size reached");
+ if (_failOnce)
+ {
+ _failAfterSend = false;
+ }
+
+ _logger.trace("Failing After Send");
+ doFailover();
+ }
+
+ if (session.getTransacted())
+ {
+ try
+ {
+ if (_failBeforeCommit)
+ {
+ if (_failOnce)
+ {
+ _failBeforeCommit = false;
+ }
+
+ _logger.trace("Failing Before Commit");
+ doFailover();
+ }
+
+ session.commit();
+
+ if (_failAfterCommit)
+ {
+ if (_failOnce)
+ {
+ _failAfterCommit = false;
+ }
+
+ _logger.trace("Failing After Commit");
+ doFailover();
+ }
+
+ _logger.trace("Session Commited.");
+ }
+ catch (JMSException e)
+ {
+ _logger.trace("JMSException on commit:" + e.getMessage(), e);
+
+ // Warn that the bounce back client is not available.
+ if (e.getLinkedException() instanceof AMQNoConsumersException)
+ {
+ _logger.debug("No consumers on queue.");
+ }
+
+ try
+ {
+ session.rollback();
+ _logger.trace("Message rolled back.");
+ }
+ catch (JMSException jmse)
+ {
+ _logger.trace("JMSE on rollback:" + jmse.getMessage(), jmse);
+
+ // Both commit and rollback failed. Throw the rollback exception.
+ throw jmse;
+ }
+ }
+ }
+ }
+
+ /**
+ * Sends the message to the specified destination. If the destination is null, it gets sent to the default destination
+ * of the ping producer. If an explicit destination is set, this overrides the default.
+ *
+ * @param destination The destination to send to.
+ * @param message The message to send.
+ *
+ * @throws javax.jms.JMSException All underlying JMSExceptions are allowed to fall through.
+ */
+ protected void sendMessage(Destination destination, Message message) throws JMSException
+ {
+ if (_failBeforeSend)
+ {
+ if (_failOnce)
+ {
+ _failBeforeSend = false;
+ }
+
+ _logger.trace("Failing Before Send");
+ doFailover();
+ }
+
+ if (destination == null)
+ {
+ _producer.send(message);
+ }
+ else
+ {
+ _producer.send(destination, message);
+ }
+ }
+
+ /**
+ * Prompts the user to terminate the broker, in order to test failover functionality. This method will block
+ * until the user supplied some input on the terminal.
+ */
+ protected void doFailover()
+ {
+ System.out.println("Kill Broker now then press return");
+ try
+ {
+ System.in.read();
+ }
+ catch (IOException e)
+ { }
+
+ System.out.println("Continuing.");
+ }
+
+ /**
+ * Defines a chained message listener interface that can be attached to this pinger. Whenever this pinger's
+ * {@link PingPongProducer#onMessage} method is called, the chained listener set through the
+ * {@link PingPongProducer#setChainedMessageListener} method is passed the message, and the remaining expected
+ * count of messages with that correlation id.
+ *
+ * Provided only one pinger is producing messages with that correlation id, the chained listener will always be
+ * given unique message counts. It will always be called while the producer waiting for all messages to arrive is
+ * still blocked.
+ */
+ public static interface ChainedMessageListener
+ {
+ public void onMessage(Message message, int remainingCount) throws JMSException;
+ }
+}
diff --git a/java/perftests/src/main/java/org/apache/qpid/requestreply/ServiceProvidingClient.java b/java/perftests/src/main/java/org/apache/qpid/requestreply/ServiceProvidingClient.java
deleted file mode 100644
index ddee643a76..0000000000
--- a/java/perftests/src/main/java/org/apache/qpid/requestreply/ServiceProvidingClient.java
+++ /dev/null
@@ -1,201 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.requestreply;
-
-import org.apache.log4j.Logger;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.jms.Session;
-import org.apache.qpid.jms.ConnectionListener;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.url.URLSyntaxException;
-
-import javax.jms.*;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-
-public class ServiceProvidingClient
-{
- private static final Logger _logger = Logger.getLogger(ServiceProvidingClient.class);
-
- private MessageProducer _destinationProducer;
-
- private Destination _responseDest;
-
- private AMQConnection _connection;
-
- public ServiceProvidingClient(String brokerDetails, String username, String password,
- String clientName, String virtualPath, String serviceName)
- throws AMQException, JMSException, URLSyntaxException
- {
- _connection = new AMQConnection(brokerDetails, username, password,
- clientName, virtualPath);
- _connection.setConnectionListener(new ConnectionListener()
- {
-
- public void bytesSent(long count)
- {
- }
-
- public void bytesReceived(long count)
- {
- }
-
- public boolean preFailover(boolean redirect)
- {
- return true;
- }
-
- public boolean preResubscribe()
- {
- return true;
- }
-
- public void failoverComplete()
- {
- _logger.info("App got failover complete callback");
- }
- });
- final Session session = (Session) _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- _logger.info("Service (queue) name is '" + serviceName + "'...");
-
- AMQQueue destination = new AMQQueue(serviceName);
-
- MessageConsumer consumer = session.createConsumer(destination,
- 100, true, false, null);
-
- consumer.setMessageListener(new MessageListener()
- {
- private int _messageCount;
-
- public void onMessage(Message message)
- {
- //_logger.info("Got message '" + message + "'");
-
- TextMessage tm = (TextMessage) message;
-
- try
- {
- Destination responseDest = tm.getJMSReplyTo();
- if (responseDest == null)
- {
- _logger.info("Producer not created because the response destination is null.");
- return;
- }
-
- if (!responseDest.equals(_responseDest))
- {
- _responseDest = responseDest;
-
- _logger.info("About to create a producer");
- _destinationProducer = session.createProducer(responseDest);
- _destinationProducer.setDisableMessageTimestamp(true);
- _destinationProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
- _logger.info("After create a producer");
- }
- }
- catch (JMSException e)
- {
- _logger.error("Error creating destination");
- }
- _messageCount++;
- if (_messageCount % 1000 == 0)
- {
- _logger.info("Received message total: " + _messageCount);
- _logger.info("Sending response to '" + _responseDest + "'");
- }
-
- try
- {
- String payload = "This is a response: sing together: 'Mahnah mahnah...'" + tm.getText();
- TextMessage msg = session.createTextMessage(payload);
- if (tm.propertyExists("timeSent"))
- {
- _logger.info("timeSent property set on message");
- _logger.info("timeSent value is: " + tm.getLongProperty("timeSent"));
- msg.setStringProperty("timeSent", tm.getStringProperty("timeSent"));
- }
- _destinationProducer.send(msg);
- if (_messageCount % 1000 == 0)
- {
- _logger.info("Sent response to '" + _responseDest + "'");
- }
- }
- catch (JMSException e)
- {
- _logger.error("Error sending message: " + e, e);
- }
- }
- });
- }
-
- public void run() throws JMSException
- {
- _connection.start();
- _logger.info("Waiting...");
- }
-
- public static void main(String[] args)
- {
- _logger.info("Starting...");
-
- if (args.length < 5)
- {
- System.out.println("Usage: brokerDetails username password virtual-path serviceQueue [selector]");
- System.exit(1);
- }
- String clientId = null;
- try
- {
- InetAddress address = InetAddress.getLocalHost();
- clientId = address.getHostName() + System.currentTimeMillis();
- }
- catch (UnknownHostException e)
- {
- _logger.error("Error: " + e, e);
- }
-
- try
- {
- ServiceProvidingClient client = new ServiceProvidingClient(args[0], args[1], args[2],
- clientId, args[3], args[4]);
- client.run();
- }
- catch (JMSException e)
- {
- _logger.error("Error: " + e, e);
- }
- catch (AMQException e)
- {
- _logger.error("Error: " + e, e);
- }
- catch (URLSyntaxException e)
- {
- _logger.error("Error: " + e, e);
- }
-
-
-
- }
-
-}
-
diff --git a/java/perftests/src/main/java/org/apache/qpid/requestreply/ServiceRequestingClient.java b/java/perftests/src/main/java/org/apache/qpid/requestreply/ServiceRequestingClient.java
deleted file mode 100644
index b52d06558a..0000000000
--- a/java/perftests/src/main/java/org/apache/qpid/requestreply/ServiceRequestingClient.java
+++ /dev/null
@@ -1,303 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.requestreply;
-
-import org.apache.log4j.Logger;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.url.URLSyntaxException;
-import org.apache.qpid.client.AMQConnection;
-import org.apache.qpid.client.AMQQueue;
-import org.apache.qpid.client.AMQDestination;
-import org.apache.qpid.jms.MessageConsumer;
-import org.apache.qpid.jms.MessageProducer;
-import org.apache.qpid.jms.Session;
-
-import javax.jms.*;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-
-/**
- * A client that behaves as follows:
- * <ul><li>Connects to a queue, whose name is specified as a cmd-line argument</li>
- * <li>Creates a temporary queue</li>
- * <li>Creates messages containing a property that is the name of the temporary queue</li>
- * <li>Fires off a message on the original queue and waits for a response on the temporary queue</li>
- * </ul>
- *
- */
-public class ServiceRequestingClient implements ExceptionListener
-{
- private static final Logger _log = Logger.getLogger(ServiceRequestingClient.class);
-
- private static final String MESSAGE_DATA_BYTES = "jfd ghljgl hjvhlj cvhvjf ldhfsj lhfdsjf hldsjfk hdslkfj hsdflk ";
-
- private String MESSAGE_DATA;
-
- private AMQConnection _connection;
-
- private Session _session;
-
- private long _averageLatency;
-
- private int _messageCount;
-
- private volatile boolean _completed;
-
- private AMQDestination _tempDestination;
-
- private MessageProducer _producer;
-
- private Object _waiter;
-
- private static String createMessagePayload(int size)
- {
- _log.info("Message size set to " + size + " bytes");
- StringBuffer buf = new StringBuffer(size);
- int count = 0;
- while (count < size + MESSAGE_DATA_BYTES.length())
- {
- buf.append(MESSAGE_DATA_BYTES);
- count += MESSAGE_DATA_BYTES.length();
- }
- if (count < size)
- {
- buf.append(MESSAGE_DATA_BYTES, 0, size - count);
- }
-
- return buf.toString();
- }
-
- private class CallbackHandler implements MessageListener
- {
- private int _expectedMessageCount;
-
- private int _actualMessageCount;
-
- private long _startTime;
-
- public CallbackHandler(int expectedMessageCount, long startTime)
- {
- _expectedMessageCount = expectedMessageCount;
- _startTime = startTime;
- }
-
- public void onMessage(Message m)
- {
- if (_log.isDebugEnabled())
- {
- _log.debug("Message received: " + m);
- }
- try
- {
- m.getPropertyNames();
- if (m.propertyExists("timeSent"))
- {
- long timeSent = Long.parseLong(m.getStringProperty("timeSent"));
- long now = System.currentTimeMillis();
- if (_averageLatency == 0)
- {
- _averageLatency = now - timeSent;
- _log.info("Latency " + _averageLatency);
- }
- else
- {
- _log.info("Individual latency: " + (now - timeSent));
- _averageLatency = (_averageLatency + (now - timeSent)) / 2;
- _log.info("Average latency now: " + _averageLatency);
- }
- }
- }
- catch (JMSException e)
- {
- _log.error("Error getting latency data: " + e, e);
- }
- _actualMessageCount++;
- if (_actualMessageCount % 1000 == 0)
- {
- _log.info("Received message count: " + _actualMessageCount);
- }
-
- if (_actualMessageCount == _expectedMessageCount)
- {
- _completed = true;
- notifyWaiter();
- long timeTaken = System.currentTimeMillis() - _startTime;
- _log.info("Total time taken to receive " + _expectedMessageCount + " messages was " +
- timeTaken + "ms, equivalent to " +
- (_expectedMessageCount / (timeTaken / 1000.0)) + " messages per second");
-
- try
- {
- _connection.close();
- _log.info("Connection closed");
- }
- catch (JMSException e)
- {
- _log.error("Error closing connection");
- }
- }
- }
- }
-
- private void notifyWaiter()
- {
- if (_waiter != null)
- {
- synchronized (_waiter)
- {
- _waiter.notify();
- }
- }
- }
- public ServiceRequestingClient(String brokerHosts, String clientID, String username, String password,
- String vpath, String commandQueueName,
- final int messageCount, final int messageDataLength) throws AMQException, URLSyntaxException
- {
- _messageCount = messageCount;
- MESSAGE_DATA = createMessagePayload(messageDataLength);
- try
- {
- createConnection(brokerHosts, clientID, username, password, vpath);
- _session = (Session) _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
-
- _connection.setExceptionListener(this);
-
-
- AMQQueue destination = new AMQQueue(commandQueueName);
- _producer = (MessageProducer) _session.createProducer(destination);
- _producer.setDisableMessageTimestamp(true);
- _producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
-
- _tempDestination = new AMQQueue("TempResponse" +
- Long.toString(System.currentTimeMillis()), true);
- MessageConsumer messageConsumer = (MessageConsumer) _session.createConsumer(_tempDestination, 100, true,
- true, null);
-
- //Send first message, then wait a bit to allow the provider to get initialised
- TextMessage first = _session.createTextMessage(MESSAGE_DATA);
- first.setJMSReplyTo(_tempDestination);
- _producer.send(first);
- try
- {
- Thread.sleep(1000);
- }
- catch (InterruptedException ignore)
- {
- }
-
- //now start the clock and the test...
- final long startTime = System.currentTimeMillis();
-
- messageConsumer.setMessageListener(new CallbackHandler(messageCount, startTime));
- }
- catch (JMSException e)
- {
- e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
- }
- }
-
- /**
- * Run the test and notify an object upon receipt of all responses.
- * @param waiter the object that will be notified
- * @throws JMSException
- */
- public void run(Object waiter) throws JMSException
- {
- _waiter = waiter;
- _connection.start();
- for (int i = 1; i < _messageCount; i++)
- {
- TextMessage msg = _session.createTextMessage(MESSAGE_DATA + i);
- msg.setJMSReplyTo(_tempDestination);
- if (i % 1000 == 0)
- {
- long timeNow = System.currentTimeMillis();
- msg.setStringProperty("timeSent", String.valueOf(timeNow));
- }
- _producer.send(msg);
- }
- _log.info("Finished sending " + _messageCount + " messages");
- }
-
- public boolean isCompleted()
- {
- return _completed;
- }
-
- private void createConnection(String brokerHosts, String clientID, String username, String password,
- String vpath) throws AMQException, URLSyntaxException
- {
- _connection = new AMQConnection(brokerHosts, username, password,
- clientID, vpath);
- }
-
- /**
- * @param args argument 1 if present specifies the name of the temporary queue to create. Leaving it blank
- * means the server will allocate a name.
- */
- public static void main(String[] args)
- {
- if (args.length < 6)
- {
- System.err.println(
- "Usage: ServiceRequestingClient <brokerDetails - semicolon separated host:port list> <username> <password> <vpath> <command queue name> <number of messages> <message size>");
- }
- try
- {
- int messageDataLength = args.length > 6 ? Integer.parseInt(args[6]) : 4096;
-
- InetAddress address = InetAddress.getLocalHost();
- String clientID = address.getHostName() + System.currentTimeMillis();
- ServiceRequestingClient client = new ServiceRequestingClient(args[0], clientID, args[1], args[2], args[3],
- args[4], Integer.parseInt(args[5]),
- messageDataLength);
- Object waiter = new Object();
- client.run(waiter);
- synchronized (waiter)
- {
- while (!client.isCompleted())
- {
- waiter.wait();
- }
- }
-
- }
- catch (UnknownHostException e)
- {
- e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
- }
- catch (Exception e)
- {
- System.err.println("Error in client: " + e);
- e.printStackTrace();
- }
- }
-
- /**
- * @see javax.jms.ExceptionListener#onException(javax.jms.JMSException)
- */
- public void onException(JMSException e)
- {
- System.err.println(e.getMessage());
- e.printStackTrace(System.err);
- }
-}
diff --git a/java/perftests/src/main/java/org/apache/qpid/topic/Config.java b/java/perftests/src/main/java/org/apache/qpid/topic/Config.java
index bb740f9094..60aa9f3930 100644
--- a/java/perftests/src/main/java/org/apache/qpid/topic/Config.java
+++ b/java/perftests/src/main/java/org/apache/qpid/topic/Config.java
@@ -22,14 +22,12 @@ package org.apache.qpid.topic;
import org.apache.qpid.client.AMQSession;
import org.apache.qpid.config.ConnectorConfig;
-import org.apache.qpid.config.ConnectionFactoryInitialiser;
import org.apache.qpid.config.Connector;
import org.apache.qpid.config.AbstractConfig;
import javax.jms.Connection;
-import javax.jms.ConnectionFactory;
-class Config extends AbstractConfig implements ConnectorConfig
+public class Config extends AbstractConfig implements ConnectorConfig
{
private String host = "localhost";
@@ -45,23 +43,30 @@ class Config extends AbstractConfig implements ConnectorConfig
private int ackMode= AMQSession.NO_ACKNOWLEDGE;
private String clientId;
private String subscriptionId;
+ private String selector;
+ private String destinationName;
private boolean persistent;
+ private boolean transacted;
+ private int destinationsCount;
+ private int batchSize;
+ private int rate;
+ private boolean ispubsub;
public Config()
{
}
- int getAckMode()
+ public int getAckMode()
{
return ackMode;
}
- void setPayload(int payload)
+ public void setPayload(int payload)
{
this.payload = payload;
}
- int getPayload()
+ public int getPayload()
{
return payload;
}
@@ -81,11 +86,26 @@ class Config extends AbstractConfig implements ConnectorConfig
this.messages = messages;
}
- int getMessages()
+ public int getMessages()
{
return messages;
}
+ public int getBatchSize()
+ {
+ return batchSize;
+ }
+
+ public int getRate()
+ {
+ return rate;
+ }
+
+ public int getDestinationsCount()
+ {
+ return destinationsCount;
+ }
+
public String getHost()
{
return host;
@@ -141,21 +161,41 @@ class Config extends AbstractConfig implements ConnectorConfig
this.delay = delay;
}
- String getClientId()
+ public String getClientId()
{
return clientId;
}
- String getSubscriptionId()
+ public String getSubscriptionId()
{
return subscriptionId;
}
- boolean usePersistentMessages()
+ public String getSelector()
+ {
+ return selector;
+ }
+
+ public String getDestination()
+ {
+ return destinationName;
+ }
+
+ public boolean usePersistentMessages()
{
return persistent;
}
+ public boolean isTransacted()
+ {
+ return transacted;
+ }
+
+ public boolean isPubSub()
+ {
+ return ispubsub;
+ }
+
public void setOption(String key, String value)
{
if("-host".equalsIgnoreCase(key))
@@ -217,6 +257,34 @@ class Config extends AbstractConfig implements ConnectorConfig
{
persistent = "true".equalsIgnoreCase(value);
}
+ else if("-transacted".equalsIgnoreCase(key))
+ {
+ transacted = "true".equalsIgnoreCase(value);
+ }
+ else if ("-destinationscount".equalsIgnoreCase(key))
+ {
+ destinationsCount = parseInt("Bad destinations count", value);
+ }
+ else if ("-batchsize".equalsIgnoreCase(key))
+ {
+ batchSize = parseInt("Bad batch size", value);
+ }
+ else if ("-rate".equalsIgnoreCase(key))
+ {
+ rate = parseInt("MEssage rate", value);
+ }
+ else if("-pubsub".equalsIgnoreCase(key))
+ {
+ ispubsub = "true".equalsIgnoreCase(value);
+ }
+ else if("-selector".equalsIgnoreCase(key))
+ {
+ selector = value;
+ }
+ else if("-destinationname".equalsIgnoreCase(key))
+ {
+ destinationName = value;
+ }
else
{
System.out.println("Ignoring unrecognised option: " + key);
diff --git a/java/perftests/src/main/java/org/apache/qpid/topic/Publisher.java b/java/perftests/src/main/java/org/apache/qpid/topic/Publisher.java
index d788029ee9..c3b19b558a 100644
--- a/java/perftests/src/main/java/org/apache/qpid/topic/Publisher.java
+++ b/java/perftests/src/main/java/org/apache/qpid/topic/Publisher.java
@@ -51,7 +51,7 @@ public class Publisher implements MessageListener
_factory.createControlConsumer().setMessageListener(this);
_connection.start();
- if(warmup > 0)
+ if (warmup > 0)
{
System.out.println("Runing warmup (" + warmup + " msgs)");
long time = batch(warmup, consumerCount);
@@ -59,11 +59,14 @@ public class Publisher implements MessageListener
}
long[] times = new long[batches];
- for(int i = 0; i < batches; i++)
+ for (int i = 0; i < batches; i++)
{
- if(i > 0) Thread.sleep(delay*1000);
+ if (i > 0)
+ {
+ Thread.sleep(delay * 1000);
+ }
times[i] = batch(msgCount, consumerCount);
- System.out.println("Batch " + (i+1) + " of " + batches + " completed in " + times[i] + " ms.");
+ System.out.println("Batch " + (i + 1) + " of " + batches + " completed in " + times[i] + " ms.");
}
long min = min(times);
@@ -131,7 +134,7 @@ public class Publisher implements MessageListener
static long min(long[] times)
{
long min = times.length > 0 ? times[0] : 0;
- for(int i = 0; i < times.length; i++)
+ for (int i = 0; i < times.length; i++)
{
min = Math.min(min, times[i]);
}
@@ -141,7 +144,7 @@ public class Publisher implements MessageListener
static long max(long[] times)
{
long max = times.length > 0 ? times[0] : 0;
- for(int i = 0; i < times.length; i++)
+ for (int i = 0; i < times.length; i++)
{
max = Math.max(max, times[i]);
}
@@ -151,14 +154,22 @@ public class Publisher implements MessageListener
static long avg(long[] times, long min, long max)
{
long sum = 0;
- for(int i = 0; i < times.length; i++)
+ for (int i = 0; i < times.length; i++)
{
sum += times[i];
}
- sum -= min;
- sum -= max;
- return (sum / (times.length - 2));
+ int adjustment = 0;
+
+ // Remove min and max if we have run enough batches.
+ if (times.length > 2)
+ {
+ sum -= min;
+ sum -= max;
+ adjustment = 2;
+ }
+
+ return (sum / (times.length - adjustment));
}
public static void main(String[] argv) throws Exception
diff --git a/java/perftests/src/main/java/perftests.log4j b/java/perftests/src/main/java/perftests.log4j
new file mode 100644
index 0000000000..3bd8c201f8
--- /dev/null
+++ b/java/perftests/src/main/java/perftests.log4j
@@ -0,0 +1,45 @@
+#
+# 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.
+#
+log4j.rootLogger=${root.logging.level}
+
+
+log4j.logger.org.apache.qpid=${amqj.logging.level}, console
+log4j.additivity.org.apache.qpid=false
+
+log4j.logger.org.apache.qpid.requestreply=${amqj.test.logging.level}
+log4j.logger.org.apache.qpid.pingpong=${amqj.test.logging.level}
+log4j.logger.org.apache.qpid.ping=${amqj.test.logging.level}
+log4j.logger.org.apache.qpid.topic=${amqj.test.logging.level}
+
+
+log4j.logger.uk.co.thebadgerset.junit.extensions=${badger.level}, console
+log4j.additivity.uk.co.thebadgerset.junit.extensions=false
+
+log4j.appender.console=org.apache.log4j.ConsoleAppender
+log4j.appender.console.Threshold=all
+log4j.appender.console.layout=org.apache.log4j.PatternLayout
+
+log4j.appender.console.layout.ConversionPattern=%t %d %p [%c{4}] %m%n
+#log4j.appender.console.layout.ConversionPattern=%t %p [%c] %m%n
+
+log4j.appender.fileApp=org.apache.log4j.FileAppender
+log4j.appender.fileApp.file=${log.dir}/perftests.volumetest.log
+log4j.appender.fileApp.Threshold=info
+log4j.appender.fileApp.append=false
+log4j.appender.fileApp.layout=org.apache.log4j.PatternLayout
diff --git a/java/perftests/src/test/java/org/apache/qpid/ping/PingAsyncTestPerf.java b/java/perftests/src/test/java/org/apache/qpid/ping/PingAsyncTestPerf.java
new file mode 100644
index 0000000000..e10e6353b7
--- /dev/null
+++ b/java/perftests/src/test/java/org/apache/qpid/ping/PingAsyncTestPerf.java
@@ -0,0 +1,302 @@
+/*
+ *
+ * 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.ping;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicLong;
+
+import javax.jms.JMSException;
+import javax.jms.Message;
+import javax.jms.ObjectMessage;
+
+import junit.framework.Test;
+import junit.framework.TestSuite;
+
+import org.apache.log4j.Logger;
+
+import org.apache.qpid.requestreply.PingPongProducer;
+
+import uk.co.thebadgerset.junit.extensions.TimingController;
+import uk.co.thebadgerset.junit.extensions.TimingControllerAware;
+import uk.co.thebadgerset.junit.extensions.util.ParsedProperties;
+
+/**
+ * PingAsyncTestPerf is a performance test that outputs multiple timings from its test method, using the timing controller
+ * interface supplied by the test runner from a seperate listener thread. It differs from the {@link PingTestPerf} test
+ * that it extends because it can output timings as replies are received, rather than waiting until all expected replies
+ * are received. This is less 'blocky' than the tests in {@link PingTestPerf}, and provides a truer simulation of sending
+ * and recieving clients working asynchronously.
+ *
+ * <p/><table id="crc"><caption>CRC Card</caption>
+ * <tr><td> Responsibilities <th> Collaborations
+ * <tr><td> Send many ping messages and output timings asynchronously on batches received.
+ * </table>
+ */
+public class PingAsyncTestPerf extends PingTestPerf implements TimingControllerAware
+{
+ private static Logger _logger = Logger.getLogger(PingAsyncTestPerf.class);
+
+ /** Holds the name of the property to get the test results logging batch size. */
+ public static final String TEST_RESULTS_BATCH_SIZE_PROPNAME = "BatchSize";
+
+ /** Holds the default test results logging batch size. */
+ public static final int DEFAULT_TEST_RESULTS_BATCH_SIZE = 1000;
+
+ /** Used to hold the timing controller passed from the test runner. */
+ private TimingController _timingController;
+
+ /** Used to generate unique correlation ids for each test run. */
+ private AtomicLong corellationIdGenerator = new AtomicLong();
+
+ /** Holds test specifics by correlation id. This consists of the expected number of messages and the timing controler. */
+ private Map<String, PerCorrelationId> perCorrelationIds =
+ Collections.synchronizedMap(new HashMap<String, PerCorrelationId>());
+
+ /** Holds the batched results listener, that does logging on batch boundaries. */
+ private BatchedResultsListener batchedResultsListener = null;
+
+ /**
+ * Creates a new asynchronous ping performance test with the specified name.
+ *
+ * @param name The test name.
+ */
+ public PingAsyncTestPerf(String name)
+ {
+ super(name);
+
+ // Sets up the test parameters with defaults.
+ ParsedProperties.setSysPropertyIfNull(TEST_RESULTS_BATCH_SIZE_PROPNAME,
+ Integer.toString(DEFAULT_TEST_RESULTS_BATCH_SIZE));
+ }
+
+ /**
+ * Compile all the tests into a test suite.
+ */
+ public static Test suite()
+ {
+ // Build a new test suite
+ TestSuite suite = new TestSuite("Ping Performance Tests");
+
+ // Run performance tests in read committed mode.
+ suite.addTest(new PingAsyncTestPerf("testAsyncPingOk"));
+
+ return suite;
+ }
+
+ /**
+ * Accepts a timing controller from the test runner.
+ *
+ * @param timingController The timing controller to register mutliple timings with.
+ */
+ public void setTimingController(TimingController timingController)
+ {
+ _timingController = timingController;
+ }
+
+ /**
+ * Gets the timing controller passed in by the test runner.
+ *
+ * @return The timing controller passed in by the test runner.
+ */
+ public TimingController getTimingController()
+ {
+ return _timingController;
+ }
+
+ /**
+ * Sends the specified number of pings, asynchronously outputs timings on every batch boundary, and waits until
+ * all replies have been received or a time out occurs before exiting this method.
+ *
+ * @param numPings The number of pings to send.
+ */
+ public void testAsyncPingOk(int numPings) throws Exception
+ {
+ _logger.debug("public void testAsyncPingOk(int numPings): called");
+
+ // Ensure that at least one ping was requeusted.
+ if (numPings == 0)
+ {
+ _logger.error("Number of pings requested was zero.");
+ }
+
+ // Get the per thread test setup to run the test through.
+ PerThreadSetup perThreadSetup = threadSetup.get();
+ PingClient pingClient = perThreadSetup._pingClient;
+
+ // Advance the correlation id of messages to send, to make it unique for this run.
+ String messageCorrelationId = Long.toString(corellationIdGenerator.incrementAndGet());
+ _logger.debug("messageCorrelationId = " + messageCorrelationId);
+
+ // Initialize the count and timing controller for the new correlation id.
+ PerCorrelationId perCorrelationId = new PerCorrelationId();
+ TimingController tc = getTimingController().getControllerForCurrentThread();
+ perCorrelationId._tc = tc;
+ perCorrelationId._expectedCount = numPings;
+ perCorrelationIds.put(messageCorrelationId, perCorrelationId);
+
+ // Attach the chained message listener to the ping producer to listen asynchronously for the replies to these
+ // messages.
+ pingClient.setChainedMessageListener(batchedResultsListener);
+
+ // Generate a sample message of the specified size.
+ ObjectMessage msg =
+ pingClient.getTestMessage(perThreadSetup._pingClient.getReplyDestinations().get(0),
+ testParameters.getPropertyAsInteger(PingPongProducer.MESSAGE_SIZE_PROPNAME),
+ testParameters.getPropertyAsBoolean(PingPongProducer.PERSISTENT_MODE_PROPNAME));
+
+ // Send the requested number of messages, and wait until they have all been received.
+ long timeout = Long.parseLong(testParameters.getProperty(PingPongProducer.TIMEOUT_PROPNAME));
+ int numReplies = pingClient.pingAndWaitForReply(msg, numPings, timeout);
+
+ // Check that all the replies were received and log a fail if they were not.
+ if (numReplies < numPings)
+ {
+ tc.completeTest(false, 0);
+ }
+
+ // Remove the chained message listener from the ping producer.
+ pingClient.removeChainedMessageListener();
+
+ // Remove the expected count and timing controller for the message correlation id, to ensure they are cleaned up.
+ perCorrelationIds.remove(messageCorrelationId);
+ }
+
+ /**
+ * Performs test fixture creation on a per thread basis. This will only be called once for each test thread.
+ */
+ public void threadSetUp()
+ {
+ _logger.debug("public void threadSetUp(): called");
+
+ try
+ {
+ // Call the set up method in the super class. This creates a PingClient pinger.
+ super.threadSetUp();
+
+ // Create the chained message listener, only if it has not already been created. This is set up with the
+ // batch size property, to tell it what batch size to output results on. A synchronized block is used to
+ // ensure that only one thread creates this.
+ synchronized (this)
+ {
+ if (batchedResultsListener == null)
+ {
+ int batchSize = Integer.parseInt(testParameters.getProperty(TEST_RESULTS_BATCH_SIZE_PROPNAME));
+ batchedResultsListener = new BatchedResultsListener(batchSize);
+ }
+ }
+
+ // Get the set up that the super class created.
+ PerThreadSetup perThreadSetup = threadSetup.get();
+
+ // Register the chained message listener on the pinger to do its asynchronous test timings from.
+ perThreadSetup._pingClient.setChainedMessageListener(batchedResultsListener);
+ }
+ catch (Exception e)
+ {
+ _logger.warn("There was an exception during per thread setup.", e);
+ }
+ }
+
+ /**
+ * BatchedResultsListener is a {@link PingPongProducer.ChainedMessageListener} that can be attached to the
+ * pinger, in order to receive notifications about every message received and the number remaining to be
+ * received. Whenever the number remaining crosses a batch size boundary this results listener outputs
+ * a test timing for the actual number of messages received in the current batch.
+ */
+ private class BatchedResultsListener implements PingPongProducer.ChainedMessageListener
+ {
+ /** The test results logging batch size. */
+ int _batchSize;
+
+ /**
+ * Creates a results listener on the specified batch size.
+ *
+ * @param batchSize The batch size to use.
+ */
+ public BatchedResultsListener(int batchSize)
+ {
+ _batchSize = batchSize;
+ }
+
+ /**
+ * This callback method is called from all of the pingers that this test creates. It uses the correlation id
+ * from the message to identify the timing controller for the test thread that was responsible for sending those
+ * messages.
+ *
+ * @param message The message.
+ * @param remainingCount The count of messages remaining to be received with a particular correlation id.
+ *
+ * @throws JMSException Any underlying JMSException is allowed to fall through.
+ */
+ public void onMessage(Message message, int remainingCount) throws JMSException
+ {
+ _logger.debug("public void onMessage(Message message, int remainingCount = " + remainingCount + "): called");
+
+ // Check if a batch boundary has been crossed.
+ if ((remainingCount % _batchSize) == 0)
+ {
+ // Extract the correlation id from the message.
+ String correlationId = message.getJMSCorrelationID();
+
+ // Get the details for the correlation id and check that they are not null. They can become null
+ // if a test times out.
+ PerCorrelationId perCorrelationId = perCorrelationIds.get(correlationId);
+ if (perCorrelationId != null)
+ {
+ // Get the timing controller and expected count for this correlation id.
+ TimingController tc = perCorrelationId._tc;
+ int expected = perCorrelationId._expectedCount;
+
+ // Calculate how many messages were actually received in the last batch. This will be the batch size
+ // except where the number expected is not a multiple of the batch size and this is the first remaining
+ // count to cross a batch size boundary, in which case it will be the number expected modulo the batch
+ // size.
+ int receivedInBatch = ((expected - remainingCount) < _batchSize) ? (expected % _batchSize) : _batchSize;
+
+ // Register a test result for the correlation id.
+ try
+ {
+
+ tc.completeTest(true, receivedInBatch);
+ }
+ catch (InterruptedException e)
+ {
+ // Ignore this. It means the test runner wants to stop as soon as possible.
+ _logger.warn("Got InterruptedException.", e);
+ }
+ }
+ // Else ignore, test timed out. Should log a fail here?
+ }
+ }
+ }
+
+ /**
+ * Holds state specific to each correlation id, needed to output test results. This consists of the count of
+ * the total expected number of messages, and the timing controller for the thread sending those message ids.
+ */
+ private static class PerCorrelationId
+ {
+ public int _expectedCount;
+ public TimingController _tc;
+ }
+}
diff --git a/java/perftests/src/test/java/org/apache/qpid/ping/PingLatencyTestPerf.java b/java/perftests/src/test/java/org/apache/qpid/ping/PingLatencyTestPerf.java
new file mode 100644
index 0000000000..620ddd13f7
--- /dev/null
+++ b/java/perftests/src/test/java/org/apache/qpid/ping/PingLatencyTestPerf.java
@@ -0,0 +1,317 @@
+/*
+ *
+ * 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.ping;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicLong;
+
+import javax.jms.JMSException;
+import javax.jms.Message;
+import javax.jms.ObjectMessage;
+
+import junit.framework.Test;
+import junit.framework.TestSuite;
+
+import org.apache.log4j.Logger;
+
+import org.apache.qpid.requestreply.PingPongProducer;
+
+import uk.co.thebadgerset.junit.extensions.TimingController;
+import uk.co.thebadgerset.junit.extensions.TimingControllerAware;
+import uk.co.thebadgerset.junit.extensions.util.ParsedProperties;
+
+/**
+ * PingLatencyTestPerf is a performance test that outputs multiple timings from its test method, using the timing
+ * controller interface supplied by the test runner from a seperate listener thread. It outputs round trip timings for
+ * individual ping messages rather than for how long a complete batch of messages took to process. It also differs from
+ * the {@link PingTestPerf} test that it extends because it can output timings as replies are received, rather than
+ * waiting until all expected replies are received.
+ *
+ * <p/>This test does not output timings for every single ping message, as when running at high volume, writing the test
+ * log for a vast number of messages would slow the testing down. Instead samples ping latency occasionally. The frequency
+ * of ping sampling is set using the {@link #TEST_RESULTS_BATCH_SIZE_PROPNAME} property, to override the default of every
+ * {@link #DEFAULT_TEST_RESULTS_BATCH_SIZE}.
+ *
+ * <p/>The size parameter logged for each individual ping is set to the size of the batch of messages that the individual
+ * timed ping was taken from, rather than 1 for a single message. This is so that the total throughput (messages / time)
+ * can be calculated in order to examine the relationship between throughput and latency.
+ *
+ * <p/><table id="crc"><caption>CRC Card</caption>
+ * <tr><td> Responsibilities <th> Collaborations
+ * <tr><td> Send many ping messages and output timings for sampled individual pings.
+ * </table>
+ */
+public class PingLatencyTestPerf extends PingTestPerf implements TimingControllerAware
+{
+ private static Logger _logger = Logger.getLogger(PingLatencyTestPerf.class);
+
+ /** Holds the name of the property to get the test results logging batch size. */
+ public static final String TEST_RESULTS_BATCH_SIZE_PROPNAME = "BatchSize";
+
+ /** Holds the default test results logging batch size. */
+ public static final int DEFAULT_TEST_RESULTS_BATCH_SIZE = 1000;
+
+ /** Used to hold the timing controller passed from the test runner. */
+ private TimingController _timingController;
+
+ /** Used to generate unique correlation ids for each test run. */
+ private AtomicLong corellationIdGenerator = new AtomicLong();
+
+ /** Holds test specifics by correlation id. This consists of the expected number of messages and the timing controler. */
+ private Map<String, PerCorrelationId> perCorrelationIds =
+ Collections.synchronizedMap(new HashMap<String, PerCorrelationId>());
+
+ /** Holds the batched results listener, that does logging on batch boundaries. */
+ private BatchedResultsListener batchedResultsListener = null;
+
+ /**
+ * Creates a new asynchronous ping performance test with the specified name.
+ *
+ * @param name The test name.
+ */
+ public PingLatencyTestPerf(String name)
+ {
+ super(name);
+
+ // Sets up the test parameters with defaults.
+ ParsedProperties.setSysPropertyIfNull(TEST_RESULTS_BATCH_SIZE_PROPNAME,
+ Integer.toString(DEFAULT_TEST_RESULTS_BATCH_SIZE));
+ }
+
+ /**
+ * Compile all the tests into a test suite.
+ */
+ public static Test suite()
+ {
+ // Build a new test suite
+ TestSuite suite = new TestSuite("Ping Latency Tests");
+
+ // Run performance tests in read committed mode.
+ suite.addTest(new PingLatencyTestPerf("testPingLatency"));
+
+ return suite;
+ }
+
+ /**
+ * Accepts a timing controller from the test runner.
+ *
+ * @param timingController The timing controller to register mutliple timings with.
+ */
+ public void setTimingController(TimingController timingController)
+ {
+ _timingController = timingController;
+ }
+
+ /**
+ * Gets the timing controller passed in by the test runner.
+ *
+ * @return The timing controller passed in by the test runner.
+ */
+ public TimingController getTimingController()
+ {
+ return _timingController;
+ }
+
+ /**
+ * Sends the specified number of pings, asynchronously outputs timings on every batch boundary, and waits until
+ * all replies have been received or a time out occurs before exiting this method.
+ *
+ * @param numPings The number of pings to send.
+ */
+ public void testPingLatency(int numPings) throws Exception
+ {
+ _logger.debug("public void testPingLatency(int numPings): called");
+
+ // Ensure that at least one ping was requeusted.
+ if (numPings == 0)
+ {
+ _logger.error("Number of pings requested was zero.");
+ }
+
+ // Get the per thread test setup to run the test through.
+ PerThreadSetup perThreadSetup = threadSetup.get();
+ PingClient pingClient = perThreadSetup._pingClient;
+
+ // Advance the correlation id of messages to send, to make it unique for this run.
+ String messageCorrelationId = Long.toString(corellationIdGenerator.incrementAndGet());
+ _logger.debug("messageCorrelationId = " + messageCorrelationId);
+
+ // Initialize the count and timing controller for the new correlation id.
+ PerCorrelationId perCorrelationId = new PerCorrelationId();
+ TimingController tc = getTimingController().getControllerForCurrentThread();
+ perCorrelationId._tc = tc;
+ perCorrelationId._expectedCount = numPings;
+ perCorrelationIds.put(messageCorrelationId, perCorrelationId);
+
+ // Attach the chained message listener to the ping producer to listen asynchronously for the replies to these
+ // messages.
+ pingClient.setChainedMessageListener(batchedResultsListener);
+
+ // Generate a sample message of the specified size.
+ ObjectMessage msg =
+ pingClient.getTestMessage(perThreadSetup._pingClient.getReplyDestinations().get(0),
+ testParameters.getPropertyAsInteger(PingPongProducer.MESSAGE_SIZE_PROPNAME),
+ testParameters.getPropertyAsBoolean(PingPongProducer.PERSISTENT_MODE_PROPNAME));
+
+ // Send the requested number of messages, and wait until they have all been received.
+ long timeout = Long.parseLong(testParameters.getProperty(PingPongProducer.TIMEOUT_PROPNAME));
+ int numReplies = pingClient.pingAndWaitForReply(msg, numPings, timeout);
+
+ // Check that all the replies were received and log a fail if they were not.
+ if (numReplies < numPings)
+ {
+ tc.completeTest(false, 0);
+ }
+
+ // Remove the chained message listener from the ping producer.
+ pingClient.removeChainedMessageListener();
+
+ // Remove the expected count and timing controller for the message correlation id, to ensure they are cleaned up.
+ perCorrelationIds.remove(messageCorrelationId);
+ }
+
+ /**
+ * Performs test fixture creation on a per thread basis. This will only be called once for each test thread.
+ */
+ public void threadSetUp()
+ {
+ _logger.debug("public void threadSetUp(): called");
+
+ try
+ {
+ // Call the set up method in the super class. This creates a PingClient pinger.
+ super.threadSetUp();
+
+ // Create the chained message listener, only if it has not already been created. This is set up with the
+ // batch size property, to tell it what batch size to output results on. A synchronized block is used to
+ // ensure that only one thread creates this.
+ synchronized (this)
+ {
+ if (batchedResultsListener == null)
+ {
+ int batchSize = Integer.parseInt(testParameters.getProperty(TEST_RESULTS_BATCH_SIZE_PROPNAME));
+ batchedResultsListener = new BatchedResultsListener(batchSize);
+ }
+ }
+
+ // Get the set up that the super class created.
+ PerThreadSetup perThreadSetup = threadSetup.get();
+
+ // Register the chained message listener on the pinger to do its asynchronous test timings from.
+ perThreadSetup._pingClient.setChainedMessageListener(batchedResultsListener);
+ }
+ catch (Exception e)
+ {
+ _logger.warn("There was an exception during per thread setup.", e);
+ }
+ }
+
+ /**
+ * BatchedResultsListener is a {@link org.apache.qpid.requestreply.PingPongProducer.ChainedMessageListener} that can
+ * be attached to the pinger, in order to receive notifications about every message received and the number remaining
+ * to be received. Whenever the number remaining crosses a batch size boundary this results listener outputs a test
+ * timing for the actual number of messages received in the current batch.
+ */
+ private class BatchedResultsListener implements PingPongProducer.ChainedMessageListener
+ {
+ /** The test results logging batch size. */
+ int _batchSize;
+
+ /**
+ * Creates a results listener on the specified batch size.
+ *
+ * @param batchSize The batch size to use.
+ */
+ public BatchedResultsListener(int batchSize)
+ {
+ _batchSize = batchSize;
+ }
+
+ /**
+ * This callback method is called from all of the pingers that this test creates. It uses the correlation id
+ * from the message to identify the timing controller for the test thread that was responsible for sending those
+ * messages.
+ *
+ * @param message The message.
+ * @param remainingCount The count of messages remaining to be received with a particular correlation id.
+ *
+ * @throws javax.jms.JMSException Any underlying JMSException is allowed to fall through.
+ */
+ public void onMessage(Message message, int remainingCount) throws JMSException
+ {
+ _logger.debug("public void onMessage(Message message, int remainingCount = " + remainingCount + "): called");
+
+ // Check if a batch boundary has been crossed.
+ if ((remainingCount % _batchSize) == 0)
+ {
+ // Extract the correlation id from the message.
+ String correlationId = message.getJMSCorrelationID();
+
+ // Get the details for the correlation id and check that they are not null. They can become null
+ // if a test times out.
+ PerCorrelationId perCorrelationId = perCorrelationIds.get(correlationId);
+ if (perCorrelationId != null)
+ {
+ // Get the timing controller and expected count for this correlation id.
+ TimingController tc = perCorrelationId._tc;
+ int expected = perCorrelationId._expectedCount;
+
+ // Extract the send time from the message and work out from the current time, what the ping latency was.
+ // The ping producer time stamps messages in nanoseconds.
+ long startTime = message.getLongProperty(PingPongProducer.MESSAGE_TIMESTAMP_PROPNAME);
+ long now = System.nanoTime();
+ long pingTime = now - startTime;
+
+ // Calculate how many messages were actually received in the last batch. This will be the batch size
+ // except where the number expected is not a multiple of the batch size and this is the first remaining
+ // count to cross a batch size boundary, in which case it will be the number expected modulo the batch
+ // size.
+ int receivedInBatch = ((expected - remainingCount) < _batchSize) ? (expected % _batchSize) : _batchSize;
+
+ // Register a test result for the correlation id.
+ try
+ {
+
+ tc.completeTest(true, receivedInBatch, pingTime);
+ }
+ catch (InterruptedException e)
+ {
+ // Ignore this. It means the test runner wants to stop as soon as possible.
+ _logger.warn("Got InterruptedException.", e);
+ }
+ }
+ // Else ignore, test timed out. Should log a fail here?
+ }
+ }
+ }
+
+ /**
+ * Holds state specific to each correlation id, needed to output test results. This consists of the count of
+ * the total expected number of messages, and the timing controller for the thread sending those message ids.
+ */
+ private static class PerCorrelationId
+ {
+ public int _expectedCount;
+ public TimingController _tc;
+ }
+}
diff --git a/java/perftests/src/test/java/org/apache/qpid/ping/PingTestPerf.java b/java/perftests/src/test/java/org/apache/qpid/ping/PingTestPerf.java
new file mode 100644
index 0000000000..c4e72f4bb6
--- /dev/null
+++ b/java/perftests/src/test/java/org/apache/qpid/ping/PingTestPerf.java
@@ -0,0 +1,246 @@
+/*
+ *
+ * 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.ping;
+
+import javax.jms.*;
+
+import junit.framework.Assert;
+import junit.framework.Test;
+import junit.framework.TestSuite;
+
+import org.apache.log4j.Logger;
+
+import org.apache.qpid.requestreply.PingPongProducer;
+
+import uk.co.thebadgerset.junit.extensions.AsymptoticTestCase;
+import uk.co.thebadgerset.junit.extensions.TestThreadAware;
+import uk.co.thebadgerset.junit.extensions.util.ParsedProperties;
+
+/**
+ * PingTestPerf is a ping test, that has been written with the intention of being scaled up to run many times
+ * simultaneously to simluate many clients/producers/connections.
+ *
+ * <p/>A single run of the test using the default JUnit test runner will result in the sending and timing of a single
+ * full round trip ping. This test may be scaled up using a suitable JUnit test runner.
+ *
+ * <p/>The setup/teardown cycle establishes a connection to a broker and sets up a queue to send ping messages to and a
+ * temporary queue for replies. This setup is only established once for all the test repeats/threads that may be run,
+ * except if the connection is lost in which case an attempt to re-establish the setup is made.
+ *
+ * <p/>The test cycle is: Connects to a queue, creates a temporary queue, creates messages containing a property that
+ * is the name of the temporary queue, fires off a message on the original queue and waits for a response on the
+ * temporary queue.
+ *
+ * <p/>Configurable test properties: message size, transacted or not, persistent or not. Broker connection details.
+ *
+ * <p><table id="crc"><caption>CRC Card</caption>
+ * <tr><th> Responsibilities <th> Collaborations
+ * </table>
+ *
+ * @author Rupert Smith
+ */
+public class PingTestPerf extends AsymptoticTestCase implements TestThreadAware
+{
+ private static Logger _logger = Logger.getLogger(PingTestPerf.class);
+
+ /** Thread local to hold the per-thread test setup fields. */
+ ThreadLocal<PerThreadSetup> threadSetup = new ThreadLocal<PerThreadSetup>();
+
+ /** Holds a property reader to extract the test parameters from. */
+ protected ParsedProperties testParameters = new ParsedProperties(System.getProperties());
+
+ public PingTestPerf(String name)
+ {
+ super(name);
+
+ // Sets up the test parameters with defaults.
+ ParsedProperties.setSysPropertyIfNull(PingPongProducer.COMMIT_BATCH_SIZE_PROPNAME,
+ Integer.toString(PingPongProducer.DEFAULT_TX_BATCH_SIZE));
+ ParsedProperties.setSysPropertyIfNull(PingPongProducer.MESSAGE_SIZE_PROPNAME,
+ Integer.toString(PingPongProducer.DEFAULT_MESSAGE_SIZE));
+ ParsedProperties.setSysPropertyIfNull(PingPongProducer.PING_QUEUE_NAME_PROPNAME,
+ PingPongProducer.DEFAULT_PING_DESTINATION_NAME);
+ ParsedProperties.setSysPropertyIfNull(PingPongProducer.PERSISTENT_MODE_PROPNAME,
+ Boolean.toString(PingPongProducer.DEFAULT_PERSISTENT_MODE));
+ ParsedProperties.setSysPropertyIfNull(PingPongProducer.TRANSACTED_PROPNAME,
+ Boolean.toString(PingPongProducer.DEFAULT_TRANSACTED));
+ ParsedProperties.setSysPropertyIfNull(PingPongProducer.BROKER_PROPNAME, PingPongProducer.DEFAULT_BROKER);
+ ParsedProperties.setSysPropertyIfNull(PingPongProducer.USERNAME_PROPNAME, PingPongProducer.DEFAULT_USERNAME);
+ ParsedProperties.setSysPropertyIfNull(PingPongProducer.PASSWORD_PROPNAME, PingPongProducer.DEFAULT_PASSWORD);
+ ParsedProperties.setSysPropertyIfNull(PingPongProducer.VIRTUAL_PATH_PROPNAME, PingPongProducer.DEFAULT_VIRTUAL_PATH);
+ ParsedProperties.setSysPropertyIfNull(PingPongProducer.VERBOSE_OUTPUT_PROPNAME,
+ Boolean.toString(PingPongProducer.DEFAULT_VERBOSE));
+ ParsedProperties.setSysPropertyIfNull(PingPongProducer.RATE_PROPNAME,
+ Integer.toString(PingPongProducer.DEFAULT_RATE));
+ ParsedProperties.setSysPropertyIfNull(PingPongProducer.IS_PUBSUB_PROPNAME,
+ Boolean.toString(PingPongProducer.DEFAULT_PUBSUB));
+ ParsedProperties.setSysPropertyIfNull(PingPongProducer.COMMIT_BATCH_SIZE_PROPNAME,
+ Integer.toString(PingPongProducer.DEFAULT_TX_BATCH_SIZE));
+ ParsedProperties.setSysPropertyIfNull(PingPongProducer.TIMEOUT_PROPNAME,
+ Long.toString(PingPongProducer.DEFAULT_TIMEOUT));
+ ParsedProperties.setSysPropertyIfNull(PingPongProducer.PING_DESTINATION_COUNT_PROPNAME,
+ Integer.toString(PingPongProducer.DEFAULT_DESTINATION_COUNT));
+ ParsedProperties.setSysPropertyIfNull(PingPongProducer.FAIL_AFTER_COMMIT_PROPNAME,
+ PingPongProducer.DEFAULT_FAIL_AFTER_COMMIT);
+ ParsedProperties.setSysPropertyIfNull(PingPongProducer.FAIL_BEFORE_COMMIT_PROPNAME,
+ PingPongProducer.DEFAULT_FAIL_BEFORE_COMMIT);
+ ParsedProperties.setSysPropertyIfNull(PingPongProducer.FAIL_AFTER_SEND_PROPNAME,
+ PingPongProducer.DEFAULT_FAIL_AFTER_SEND);
+ ParsedProperties.setSysPropertyIfNull(PingPongProducer.FAIL_BEFORE_SEND_PROPNAME,
+ PingPongProducer.DEFAULT_FAIL_BEFORE_SEND);
+ ParsedProperties.setSysPropertyIfNull(PingPongProducer.FAIL_ONCE_PROPNAME, PingPongProducer.DEFAULT_FAIL_ONCE);
+ }
+
+ /**
+ * Compile all the tests into a test suite.
+ */
+ public static Test suite()
+ {
+ // Build a new test suite
+ TestSuite suite = new TestSuite("Ping Performance Tests");
+
+ // Run performance tests in read committed mode.
+ suite.addTest(new PingTestPerf("testPingOk"));
+
+ return suite;
+ }
+
+ public void testPingOk(int numPings) throws Exception
+ {
+ // Get the per thread test setup to run the test through.
+ PerThreadSetup perThreadSetup = threadSetup.get();
+ if (numPings == 0)
+ {
+ _logger.error("Number of pings requested was zero.");
+ }
+
+ // Generate a sample message. This message is already time stamped and has its reply-to destination set.
+ ObjectMessage msg =
+ perThreadSetup._pingClient.getTestMessage(perThreadSetup._pingClient.getReplyDestinations().get(0),
+ testParameters.getPropertyAsInteger(
+ PingPongProducer.MESSAGE_SIZE_PROPNAME),
+ testParameters.getPropertyAsBoolean(
+ PingPongProducer.PERSISTENT_MODE_PROPNAME));
+
+ // start the test
+ long timeout = Long.parseLong(testParameters.getProperty(PingPongProducer.TIMEOUT_PROPNAME));
+ int numReplies = perThreadSetup._pingClient.pingAndWaitForReply(msg, numPings, timeout);
+
+ // Fail the test if the timeout was exceeded.
+ if (numReplies != numPings)
+ {
+ Assert.fail("The ping timed out after " + timeout + " ms. Messages Sent = " + numPings + ", MessagesReceived = "
+ + numReplies);
+ }
+ }
+
+ /**
+ * Performs test fixture creation on a per thread basis. This will only be called once for each test thread.
+ */
+ public void threadSetUp()
+ {
+ _logger.debug("public void threadSetUp(): called");
+
+ try
+ {
+ PerThreadSetup perThreadSetup = new PerThreadSetup();
+
+ // Extract the test set up paramaeters.
+ String brokerDetails = testParameters.getProperty(PingPongProducer.BROKER_PROPNAME);
+ String username = testParameters.getProperty(PingPongProducer.USERNAME_PROPNAME);
+ String password = testParameters.getProperty(PingPongProducer.PASSWORD_PROPNAME);
+ String virtualPath = testParameters.getProperty(PingPongProducer.VIRTUAL_PATH_PROPNAME);
+ String destinationName = testParameters.getProperty(PingPongProducer.PING_QUEUE_NAME_PROPNAME);
+ boolean persistent = testParameters.getPropertyAsBoolean(PingPongProducer.PERSISTENT_MODE_PROPNAME);
+ boolean transacted = testParameters.getPropertyAsBoolean(PingPongProducer.TRANSACTED_PROPNAME);
+ String selector = testParameters.getProperty(PingPongProducer.SELECTOR_PROPNAME);
+ boolean verbose = testParameters.getPropertyAsBoolean(PingPongProducer.VERBOSE_OUTPUT_PROPNAME);
+ int messageSize = testParameters.getPropertyAsInteger(PingPongProducer.MESSAGE_SIZE_PROPNAME);
+ int rate = testParameters.getPropertyAsInteger(PingPongProducer.RATE_PROPNAME);
+ boolean pubsub = testParameters.getPropertyAsBoolean(PingPongProducer.IS_PUBSUB_PROPNAME);
+ boolean failAfterCommit = testParameters.getPropertyAsBoolean(PingPongProducer.FAIL_AFTER_COMMIT_PROPNAME);
+ boolean failBeforeCommit = testParameters.getPropertyAsBoolean(PingPongProducer.FAIL_BEFORE_COMMIT_PROPNAME);
+ boolean failAfterSend = testParameters.getPropertyAsBoolean(PingPongProducer.FAIL_AFTER_SEND_PROPNAME);
+ boolean failBeforeSend = testParameters.getPropertyAsBoolean(PingPongProducer.FAIL_BEFORE_SEND_PROPNAME);
+ int batchSize = testParameters.getPropertyAsInteger(PingPongProducer.COMMIT_BATCH_SIZE_PROPNAME);
+ Boolean failOnce = testParameters.getPropertyAsBoolean(PingPongProducer.FAIL_ONCE_PROPNAME);
+
+ // Extract the test set up paramaeters.
+ int destinationscount =
+ Integer.parseInt(testParameters.getProperty(PingPongProducer.PING_DESTINATION_COUNT_PROPNAME));
+
+ // This is synchronized because there is a race condition, which causes one connection to sleep if
+ // all threads try to create connection concurrently.
+ synchronized (this)
+ {
+ // Establish a client to ping a Destination and listen the reply back from same Destination
+ perThreadSetup._pingClient = new PingClient(brokerDetails, username, password, virtualPath, destinationName,
+ selector, transacted, persistent, messageSize, verbose,
+ failAfterCommit, failBeforeCommit, failAfterSend, failBeforeSend,
+ failOnce, batchSize, destinationscount, rate, pubsub);
+ }
+ // Start the client connection
+ perThreadSetup._pingClient.getConnection().start();
+
+ // Attach the per-thread set to the thread.
+ threadSetup.set(perThreadSetup);
+ }
+ catch (Exception e)
+ {
+ _logger.warn("There was an exception during per thread setup.", e);
+ }
+ }
+
+ /**
+ * Performs test fixture clean
+ */
+ public void threadTearDown()
+ {
+ _logger.debug("public void threadTearDown(): called");
+
+ try
+ {
+ // Get the per thread test fixture.
+ PerThreadSetup perThreadSetup = threadSetup.get();
+
+ // Close the pingers so that it cleans up its connection cleanly.
+ synchronized (this)
+ {
+ perThreadSetup._pingClient.close();
+ }
+
+ // Ensure the per thread fixture is reclaimed.
+ threadSetup.remove();
+ }
+ catch (JMSException e)
+ {
+ _logger.warn("There was an exception during per thread tear down.");
+ }
+ }
+
+ protected static class PerThreadSetup
+ {
+ /**
+ * Holds the test ping client.
+ */
+ protected PingClient _pingClient;
+ }
+}
diff --git a/java/perftests/src/test/java/org/apache/qpid/requestreply/PingPongTestPerf.java b/java/perftests/src/test/java/org/apache/qpid/requestreply/PingPongTestPerf.java
new file mode 100644
index 0000000000..81967d332a
--- /dev/null
+++ b/java/perftests/src/test/java/org/apache/qpid/requestreply/PingPongTestPerf.java
@@ -0,0 +1,259 @@
+/*
+ *
+ * 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.requestreply;
+
+import javax.jms.*;
+
+import junit.framework.Assert;
+import junit.framework.Test;
+import junit.framework.TestSuite;
+
+import org.apache.log4j.Logger;
+
+import uk.co.thebadgerset.junit.extensions.AsymptoticTestCase;
+import uk.co.thebadgerset.junit.extensions.util.ParsedProperties;
+
+/**
+ * PingPongTestPerf is a full round trip ping test, that has been written with the intention of being scaled up to run
+ * many times simultaneously to simluate many clients/producer/connections. A full round trip ping sends a message from
+ * a producer to a conumer, then the consumer replies to the message on a temporary queue.
+ *
+ * <p/>A single run of the test using the default JUnit test runner will result in the sending and timing of the number
+ * of pings specified by the test size and time how long it takes for all of these to complete. This test may be scaled
+ * up using a suitable JUnit test runner. See {@link uk.co.thebadgerset.junit.extensions.TKTestRunner} for more
+ * information on how to do this.
+ *
+ * <p/>The setup/teardown cycle establishes a connection to a broker and sets up a queue to send ping messages to and a
+ * temporary queue for replies. This setup is only established once for all the test repeats, but each test threads
+ * gets its own connection/producer/consumer, this is only re-established if the connection is lost.
+ *
+ * <p/>The test cycle is: Connects to a queue, creates a temporary queue, creates messages containing a property that
+ * is the name of the temporary queue, fires off many messages on the original queue and waits for them all to come
+ * back on the temporary queue.
+ *
+ * <p/>Configurable test properties: message size, transacted or not, persistent or not. Broker connection details.
+ *
+ * <p><table id="crc"><caption>CRC Card</caption>
+ * <tr><th> Responsibilities <th> Collaborations
+ * </table>
+ *
+ * @author Rupert Smith
+ */
+public class PingPongTestPerf extends AsymptoticTestCase
+{
+ private static Logger _logger = Logger.getLogger(PingPongTestPerf.class);
+
+ /** Thread local to hold the per-thread test setup fields. */
+ ThreadLocal<PerThreadSetup> threadSetup = new ThreadLocal<PerThreadSetup>();
+
+ // Set up a property reader to extract the test parameters from. Once ContextualProperties is available in
+ // the project dependencies, use it to get property overrides for configurable tests and to notify the test runner
+ // of the test parameters to log with the results. It also providers some basic type parsing convenience methods.
+ //private Properties testParameters = System.getProperties();
+ private ParsedProperties testParameters = new ParsedProperties(System.getProperties());
+
+ public PingPongTestPerf(String name)
+ {
+ super(name);
+
+ // Sets up the test parameters with defaults.
+ ParsedProperties.setSysPropertyIfNull(PingPongProducer.COMMIT_BATCH_SIZE_PROPNAME,
+ Integer.toString(PingPongProducer.DEFAULT_TX_BATCH_SIZE));
+ ParsedProperties.setSysPropertyIfNull(PingPongProducer.MESSAGE_SIZE_PROPNAME,
+ Integer.toString(PingPongProducer.DEFAULT_MESSAGE_SIZE));
+ ParsedProperties.setSysPropertyIfNull(PingPongProducer.PING_QUEUE_NAME_PROPNAME,
+ PingPongProducer.DEFAULT_PING_DESTINATION_NAME);
+ ParsedProperties.setSysPropertyIfNull(PingPongProducer.PERSISTENT_MODE_PROPNAME,
+ Boolean.toString(PingPongProducer.DEFAULT_PERSISTENT_MODE));
+ ParsedProperties.setSysPropertyIfNull(PingPongProducer.TRANSACTED_PROPNAME,
+ Boolean.toString(PingPongProducer.DEFAULT_TRANSACTED));
+ ParsedProperties.setSysPropertyIfNull(PingPongProducer.BROKER_PROPNAME, PingPongProducer.DEFAULT_BROKER);
+ ParsedProperties.setSysPropertyIfNull(PingPongProducer.USERNAME_PROPNAME, PingPongProducer.DEFAULT_USERNAME);
+ ParsedProperties.setSysPropertyIfNull(PingPongProducer.PASSWORD_PROPNAME, PingPongProducer.DEFAULT_PASSWORD);
+ ParsedProperties.setSysPropertyIfNull(PingPongProducer.VIRTUAL_PATH_PROPNAME, PingPongProducer.DEFAULT_VIRTUAL_PATH);
+ ParsedProperties.setSysPropertyIfNull(PingPongProducer.VERBOSE_OUTPUT_PROPNAME,
+ Boolean.toString(PingPongProducer.DEFAULT_VERBOSE));
+ ParsedProperties.setSysPropertyIfNull(PingPongProducer.RATE_PROPNAME,
+ Integer.toString(PingPongProducer.DEFAULT_RATE));
+ ParsedProperties.setSysPropertyIfNull(PingPongProducer.IS_PUBSUB_PROPNAME,
+ Boolean.toString(PingPongProducer.DEFAULT_PUBSUB));
+ ParsedProperties.setSysPropertyIfNull(PingPongProducer.COMMIT_BATCH_SIZE_PROPNAME,
+ Integer.toString(PingPongProducer.DEFAULT_TX_BATCH_SIZE));
+ ParsedProperties.setSysPropertyIfNull(PingPongProducer.TIMEOUT_PROPNAME,
+ Long.toString(PingPongProducer.DEFAULT_TIMEOUT));
+ ParsedProperties.setSysPropertyIfNull(PingPongProducer.PING_DESTINATION_COUNT_PROPNAME,
+ Integer.toString(PingPongProducer.DEFAULT_DESTINATION_COUNT));
+ ParsedProperties.setSysPropertyIfNull(PingPongProducer.FAIL_AFTER_COMMIT_PROPNAME,
+ PingPongProducer.DEFAULT_FAIL_AFTER_COMMIT);
+ ParsedProperties.setSysPropertyIfNull(PingPongProducer.FAIL_BEFORE_COMMIT_PROPNAME,
+ PingPongProducer.DEFAULT_FAIL_BEFORE_COMMIT);
+ ParsedProperties.setSysPropertyIfNull(PingPongProducer.FAIL_AFTER_SEND_PROPNAME,
+ PingPongProducer.DEFAULT_FAIL_AFTER_SEND);
+ ParsedProperties.setSysPropertyIfNull(PingPongProducer.FAIL_BEFORE_SEND_PROPNAME,
+ PingPongProducer.DEFAULT_FAIL_BEFORE_SEND);
+ ParsedProperties.setSysPropertyIfNull(PingPongProducer.FAIL_ONCE_PROPNAME, PingPongProducer.DEFAULT_FAIL_ONCE);
+ }
+
+ /**
+ * Compile all the tests into a test suite.
+ */
+ public static Test suite()
+ {
+ // Build a new test suite
+ TestSuite suite = new TestSuite("Ping-Pong Performance Tests");
+
+ // Run performance tests in read committed mode.
+ suite.addTest(new PingPongTestPerf("testPingPongOk"));
+
+ return suite;
+ }
+
+ private static void setSystemPropertyIfNull(String propName, String propValue)
+ {
+ if (System.getProperty(propName) == null)
+ {
+ System.setProperty(propName, propValue);
+ }
+ }
+
+ public void testPingPongOk(int numPings) throws Exception
+ {
+ // Get the per thread test setup to run the test through.
+ PerThreadSetup perThreadSetup = threadSetup.get();
+
+ // Generate a sample message. This message is already time stamped and has its reply-to destination set.
+ ObjectMessage msg =
+ perThreadSetup._testPingProducer.getTestMessage(perThreadSetup._testPingProducer.getReplyDestinations().get(0),
+ testParameters.getPropertyAsInteger(
+ PingPongProducer.MESSAGE_SIZE_PROPNAME),
+ testParameters.getPropertyAsBoolean(
+ PingPongProducer.PERSISTENT_MODE_PROPNAME));
+
+ // Send the message and wait for a reply.
+ int numReplies =
+ perThreadSetup._testPingProducer.pingAndWaitForReply(msg, numPings, PingPongProducer.DEFAULT_TIMEOUT);
+
+ // Fail the test if the timeout was exceeded.
+ if (numReplies != numPings)
+ {
+ Assert.fail("The ping timed out, got " + numReplies + " out of " + numPings);
+ }
+ }
+
+ /**
+ * Performs test fixture creation on a per thread basis. This will only be called once for each test thread.
+ */
+ public void threadSetUp()
+ {
+ try
+ {
+ PerThreadSetup perThreadSetup = new PerThreadSetup();
+
+ // Extract the test set up paramaeters.
+ String brokerDetails = testParameters.getProperty(PingPongProducer.BROKER_PROPNAME);
+ String username = testParameters.getProperty(PingPongProducer.USERNAME_PROPNAME);
+ String password = testParameters.getProperty(PingPongProducer.PASSWORD_PROPNAME);
+ String virtualPath = testParameters.getProperty(PingPongProducer.VIRTUAL_PATH_PROPNAME);
+ String destinationName = testParameters.getProperty(PingPongProducer.PING_QUEUE_NAME_PROPNAME);
+ boolean persistent = testParameters.getPropertyAsBoolean(PingPongProducer.PERSISTENT_MODE_PROPNAME);
+ boolean transacted = testParameters.getPropertyAsBoolean(PingPongProducer.TRANSACTED_PROPNAME);
+ String selector = testParameters.getProperty(PingPongProducer.SELECTOR_PROPNAME);
+ boolean verbose = testParameters.getPropertyAsBoolean(PingPongProducer.VERBOSE_OUTPUT_PROPNAME);
+ int messageSize = testParameters.getPropertyAsInteger(PingPongProducer.MESSAGE_SIZE_PROPNAME);
+ int rate = testParameters.getPropertyAsInteger(PingPongProducer.RATE_PROPNAME);
+ boolean pubsub = testParameters.getPropertyAsBoolean(PingPongProducer.IS_PUBSUB_PROPNAME);
+ boolean failAfterCommit = testParameters.getPropertyAsBoolean(PingPongProducer.FAIL_AFTER_COMMIT_PROPNAME);
+ boolean failBeforeCommit = testParameters.getPropertyAsBoolean(PingPongProducer.FAIL_BEFORE_COMMIT_PROPNAME);
+ boolean failAfterSend = testParameters.getPropertyAsBoolean(PingPongProducer.FAIL_AFTER_SEND_PROPNAME);
+ boolean failBeforeSend = testParameters.getPropertyAsBoolean(PingPongProducer.FAIL_BEFORE_SEND_PROPNAME);
+ int batchSize = testParameters.getPropertyAsInteger(PingPongProducer.COMMIT_BATCH_SIZE_PROPNAME);
+ Boolean failOnce = testParameters.getPropertyAsBoolean(PingPongProducer.FAIL_ONCE_PROPNAME);
+
+ synchronized (this)
+ {
+ // Establish a bounce back client on the ping queue to bounce back the pings.
+ perThreadSetup._testPingBouncer = new PingPongBouncer(brokerDetails, username, password, virtualPath,
+ destinationName, persistent, transacted, selector,
+ verbose, pubsub);
+
+ // Start the connections for client and producer running.
+ perThreadSetup._testPingBouncer.getConnection().start();
+
+ // Establish a ping-pong client on the ping queue to send the pings with.
+
+ perThreadSetup._testPingProducer = new PingPongProducer(brokerDetails, username, password, virtualPath,
+ destinationName, selector, transacted, persistent,
+ messageSize, verbose, failAfterCommit,
+ failBeforeCommit, failAfterSend, failBeforeSend,
+ failOnce, batchSize, 0, rate, pubsub);
+ perThreadSetup._testPingProducer.getConnection().start();
+ }
+
+ // Attach the per-thread set to the thread.
+ threadSetup.set(perThreadSetup);
+ }
+ catch (Exception e)
+ {
+ _logger.warn("There was an exception during per thread setup.", e);
+ }
+ }
+
+ /**
+ * Performs test fixture clean
+ */
+ public void threadTearDown()
+ {
+ _logger.debug("public void threadTearDown(): called");
+
+ try
+ {
+ // Get the per thread test fixture.
+ PerThreadSetup perThreadSetup = threadSetup.get();
+
+ // Close the pingers so that it cleans up its connection cleanly.
+ synchronized (this)
+ {
+ perThreadSetup._testPingProducer.close();
+ //perThreadSetup._testPingBouncer.close();
+ }
+
+ // Ensure the per thread fixture is reclaimed.
+ threadSetup.remove();
+ }
+ catch (JMSException e)
+ {
+ _logger.warn("There was an exception during per thread tear down.");
+ }
+ }
+
+ protected static class PerThreadSetup
+ {
+ /**
+ * Holds the test ping-pong producer.
+ */
+ private PingPongProducer _testPingProducer;
+
+ /**
+ * Holds the test ping client.
+ */
+ private PingPongBouncer _testPingBouncer;
+ }
+}
diff --git a/java/pom.xml b/java/pom.xml
index 0f1f016a54..2150e61861 100644
--- a/java/pom.xml
+++ b/java/pom.xml
@@ -46,6 +46,14 @@
<name>Apache SNAPSHOT Repository</name>
<url>scp://people.apache.org/www/people.apache.org/repo/m2-snapshot-repository</url>
</snapshotRepository>
+
+ <!-- Qpid has a Wiki site, maven generated site not used. This is just so that it can be created locally for viewing the reports. -->
+ <site>
+ <id>Qpid_Site</id>
+ <name>Qpid Site</name>
+ <url>file:/temp</url>
+ </site>
+
</distributionManagement>
<inceptionYear>2006</inceptionYear>
@@ -65,6 +73,7 @@
<archive>http://mail-archives.apache.org/mod_mbox/incubator-qpid-commits</archive>
</mailingList>
</mailingLists>
+
<licenses>
<license>
<name>The Apache Software License, Version 2.0</name>
@@ -72,23 +81,33 @@
<distribution>repo</distribution>
</license>
</licenses>
+
<organization>
<name>Apache Software Foundation</name>
<url>http://www.apache.org/</url>
</organization>
+
<properties>
<topDirectoryLocation>.</topDirectoryLocation>
- <surefire.fork.mode>once</surefire.fork.mode>
+ <surefire.fork.mode>never</surefire.fork.mode>
<surefire.format>brief</surefire.format>
<surefire.usefile>false</surefire.usefile>
<compile.forked>false</compile.forked>
<java.source.version>1.5</java.source.version>
<compile.flags>-Xlint:fallthrough,finally</compile.flags>
+ <!--
+ This should always point to a default minimal log4j configuration that all developers are happy with as a useable default. To use your own
+ log4j preferences set up an alternative in your settings.xml and avoid corrupting the default with private preferences.
+ -->
+ <!--<log4j.configuration>file:/${topDirectoryLocation}/etc/log4j.xml</log4j.configuration>-->
+ <amqj.logging.level>warn</amqj.logging.level> <!-- This is referenced in the default log4j.xml -->
+
<!--Versions for various plugins and features -->
<antrun.version>1.2-SNAPSHOT</antrun.version>
- <assembly.version>2.1</assembly.version>
+ <!--<assembly.version>2.2-SNAPSHOT</assembly.version>-->
+ <assembly.version>2.1</assembly.version>
<cobertura.version>2.0</cobertura.version>
<compiler.version>2.0.1</compiler.version>
<dependency.plugin.version>1.0</dependency.plugin.version>
@@ -103,8 +122,6 @@
<surefire-report.version>2.1-SNAPSHOT</surefire-report.version>
<surefire.version>2.2</surefire.version>
- <amqj.logging.level>warn</amqj.logging.level>
-
<eclipse.workspace.dir>${basedir}/${topDirectoryLocation}/../workspace</eclipse.workspace.dir>
<clover.license.pathname>/set/clover/license/path/here</clover.license.pathname>
</properties>
@@ -115,6 +132,7 @@
<module>client</module>
<module>cluster</module>
<module>systests</module>
+ <module>perftests</module>
<module>management/eclipse-plugin</module>
</modules>
@@ -124,6 +142,7 @@
<directory>src/main/java</directory>
<excludes>
<exclude>**/*.java</exclude>
+ <exclude>**/log4j.properties</exclude>
</excludes>
</resource>
<resource>
@@ -146,6 +165,7 @@
</includes>
</resource>
</resources>
+
<testResources>
<testResource>
<directory>src/test/java</directory>
@@ -181,7 +201,6 @@
<artifactId>ant-nodeps</artifactId>
<version>1.6.5</version>
</dependency>
-
</dependencies>
<executions>
@@ -194,13 +213,13 @@
time, during the 'package' phase to capture the version of any resources added to jar files.
This svnversion command is always run in the top directory to accurately reflect the svnversion range accross all modules
at the time of the build.
- The properties are placed into a file 'qpidversion.properties' in the target/classes directory of any child module that runs
- this plugin.
+ The properties are placed into a file 'qpidversion.properties' in the target/classes directory of any child module
+ that runs this plugin.
The 'qpidversion.properties' file is loaded by the org.apache.qpid.common.QpidProperties class.
Be carefull of the possibility that the 'common' module may run this antrun plugin and recieve its own set of
- qpidversion.properties and then the client or broker being built against an older version of the common library ending up with
- the wrong version information. This is unlikely to happen because the client or broker should pick up its own properties
- from the classpath first. If this happens it will be obvious because the productName property will be
+ qpidversion.properties and then the client or broker being built against an older version of the common library ending
+ up with the wrong version information. This is unlikely to happen because the client or broker should pick up its own
+ properties from the classpath first. If this happens it will be obvious because the productName property will be
'Qpid Common Utilities'. If this is a problem then push this ant task down into the client and broker poms and remove it
from here.
-->
@@ -230,16 +249,19 @@
</execution>
</executions>
</plugin>
+
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>${jar.version}</version>
</plugin>
+
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>${resources.version}</version>
</plugin>
+
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
@@ -250,6 +272,7 @@
<fork>${compile.forked}</fork>
</configuration>
</plugin>
+
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
@@ -265,17 +288,23 @@
<argLine>-ea</argLine>
<systemproperties>
<property>
- <name>amqj.logging.level</name>
+ <name>amqj.logging.level</name>
<value>${amqj.logging.level}</value>
+ <!--
+ <name>log4j.configuration</name>
+ <value>${log4j.configuration}</value>
+ -->
</property>
</systemproperties>
</configuration>
</plugin>
+
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-site-plugin</artifactId>
<version>${site.version}</version>
</plugin>
+
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-eclipse-plugin</artifactId>
@@ -290,14 +319,16 @@
</projectnatures>
</configuration>
</plugin>
+
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-idea-plugin</artifactId>
<configuration>
- <downloadSources>true</downloadSources>
+ <!--downloadSources>true</downloadSources-->
<downloadJavadocs>true</downloadJavadocs>
</configuration>
</plugin>
+
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-clover-plugin</artifactId>
@@ -316,9 +347,19 @@
</execution>
</executions>
</plugin>
+
+ <!-- The JUnit Toolkit maven2 plugin is in the process of being added to the maven repository. -->
+ <plugin>
+ <groupId>uk.co.thebadgerset</groupId>
+ <artifactId>junit-toolkit-maven-plugin</artifactId>
+ <version>0.5-SNAPSHOT</version>
+ </plugin>
+
</plugins>
</pluginManagement>
+
<defaultGoal>install</defaultGoal>
+
</build>
<dependencyManagement>
@@ -347,13 +388,6 @@
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.1</version>
- <exclusions>
- <!-- this seems to have a junit compile dependency -->
- <exclusion>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- </exclusion>
- </exclusions>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
@@ -405,18 +439,30 @@
<artifactId>backport-util-concurrent</artifactId>
<version>2.2</version>
</dependency>
+
+ <!-- Test Dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
+
<dependency>
<groupId>org.easymock</groupId>
<artifactId>easymockclassextension</artifactId>
<version>2.2</version>
<scope>test</scope>
</dependency>
+
+ <dependency>
+ <groupId>uk.co.thebadgerset</groupId>
+ <artifactId>junit-toolkit</artifactId>
+ <version>0.5-SNAPSHOT</version>
+ <scope>compile</scope>
+ </dependency>
+
+ <!-- Qpid Version Dependencies -->
<dependency>
<groupId>org.apache.qpid</groupId>
<artifactId>qpid-common</artifactId>
@@ -434,6 +480,16 @@
</dependency>
<dependency>
<groupId>org.apache.qpid</groupId>
+ <artifactId>qpid-perftests</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.qpid</groupId>
+ <artifactId>qpid-systests</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.qpid</groupId>
<artifactId>qpid-mgmt-core</artifactId>
<version>${project.version}</version>
</dependency>
diff --git a/java/resources/DISCLAIMER b/java/resources/DISCLAIMER
new file mode 100644
index 0000000000..c321113c9e
--- /dev/null
+++ b/java/resources/DISCLAIMER
@@ -0,0 +1,5 @@
+Apache Qpid is an effort undergoing incubation at the Apache Software Foundation (ASF), sponsored by the Apache Incubator PMC.
+
+Incubation is required of all newly accepted projects until a further review indicates that the infrastructure, communications, and decision making process have stabilized in a manner consistent with other successful ASF projects.
+
+While incubation status is not necessarily a reflection of the completeness or stability of the code, it does indicate that the project has yet to be fully endorsed by the ASF.
diff --git a/java/resources/LICENSE.txt b/java/resources/LICENSE.txt
new file mode 100755
index 0000000000..6b0b1270ff
--- /dev/null
+++ b/java/resources/LICENSE.txt
@@ -0,0 +1,203 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed 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.
+
diff --git a/java/resources/NOTICE.txt b/java/resources/NOTICE.txt
new file mode 100644
index 0000000000..82d3dbc632
--- /dev/null
+++ b/java/resources/NOTICE.txt
@@ -0,0 +1,36 @@
+=========================================================================
+== NOTICE file corresponding to the section 4 d of ==
+== the Apache License, Version 2.0, ==
+== in this case for the Apache Qpid distribution. ==
+=========================================================================
+
+This product includes software developed by the Apache Software Foundation
+(http://www.apache.org/).
+
+Please read the LICENSE.txt file present in the root directory of this
+distribution.
+
+
+Aside from contributions to the Apache Qpid project, this software also
+includes (binary only):
+
+ - The SAXON XSLT Processor from Michael Kay distributed under the
+ Mozilla Public License v1.0, which is available for download at
+ http://saxon.sourceforge.net/
+
+ - The JUnit regression testing framework written by Erich Gamma
+ and Kent Beck and distributed under the Common Public License v1.0.
+ JUnit is available for download at
+ http://sourceforge.net/projects/junit/
+
+ - The Simple Logging Facade For Java (slf4j), Copyright (c)
+ 2004-2005 SLF4J.ORG, Copyright (c) 2004-2005 QOS.ch. slf4j is
+ licensed under identical terms to the MIT/X11 license and
+ available for download at http://www.slf4j.org/
+
+ - Software from the Eclipse project. The binaries from this project are
+ distributed under the Eclipse Public License and can be donwloaded
+ from http://www.eclipse.org/
+
+
+
diff --git a/java/resources/README.txt b/java/resources/README.txt
new file mode 100644
index 0000000000..1d52d487fb
--- /dev/null
+++ b/java/resources/README.txt
@@ -0,0 +1,40 @@
+
+Documentation
+--------------
+All of our user documentation for the Qpid Java components can be accessed on our wiki at:
+
+http://cwiki.apache.org/confluence/display/qpid/Qpid+Java+Documentation
+
+This includes a Getting Started Guide and FAQ as well as detailed developer documentation.
+However, here's a VERY quick guide to running the installed Qpid broker, once you have installed it somewhere !
+
+
+Running the Broker
+------------------
+
+To run the broker, set the QPID_HOME environment variable to
+distribution directory and add $QPID_HOME/bin to your PATH. Then run
+the qpid-server shell script or qpid-server.bat batch file to start
+the broker. By default, the broker will use $QPID_HOME/etc to find
+the configuration files. You can supply a custom configuration using
+the -c argument.
+
+For example:
+
+qpid-server -c ~/etc/config.xml
+
+You can get a list of all command line arguments by using the -h argument.
+
+
+Developing
+----------
+
+In order to build Qpid you need Ant 1.6.5. Use ant -p to list the
+available targets. The default ant target, build, creates a working
+development-mode distribution in the build directory. To run the
+scripts in build/bin set QPID_HOME to the build directory and put
+${QPID_HOME}/bin on your PATH. The scripts in that directory include
+the standard ones in the distribution and a number of testing scripts.
+
+
+
diff --git a/java/systests/distribution/pom.xml b/java/systests/distribution/pom.xml
new file mode 100644
index 0000000000..bff1e0d9e5
--- /dev/null
+++ b/java/systests/distribution/pom.xml
@@ -0,0 +1,111 @@
+<!--
+ 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.
+ -->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>org.apache.qpid</groupId>
+ <artifactId>qpid-systests-distribution</artifactId>
+ <packaging>jar</packaging>
+ <version>1.0-incubating-M2-SNAPSHOT</version>
+ <name>Qpid System Tests Distribution</name>
+ <url>http://cwiki.apache.org/confluence/display/qpid</url>
+
+ <parent>
+ <groupId>org.apache.qpid</groupId>
+ <artifactId>qpid</artifactId>
+ <version>1.0-incubating-M2-SNAPSHOT</version>
+ </parent>
+
+ <properties>
+ <topDirectoryLocation>..</topDirectoryLocation>
+ <java.source.version>1.5</java.source.version>
+ <qpid.version>${pom.version}</qpid.version>
+ <qpid.targetDir>${project.build.directory}</qpid.targetDir>
+ </properties>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.qpid</groupId>
+ <artifactId>qpid-systests</artifactId>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <pluginManagement>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <configuration>
+ <source>${java.source.version}</source>
+ <target>${java.source.version}</target>
+ </configuration>
+ </plugin>
+
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-assembly-plugin</artifactId>
+ <version>${assembly.version}</version>
+ <configuration>
+ <finalName>qpid-${pom.version}</finalName>
+ <outputDirectory>${qpid.targetDir}</outputDirectory>
+ <tarLongFileMode>gnu</tarLongFileMode>
+ </configuration>
+ </plugin>
+
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-jar-plugin</artifactId>
+ <configuration>
+ <finalName>qpid-systests</finalName>
+ <archive>
+ <manifest>
+ <addClasspath>true</addClasspath>
+ </manifest>
+ </archive>
+ </configuration>
+ </plugin>
+
+ </plugins>
+ </pluginManagement>
+
+ <plugins>
+ <plugin>
+ <artifactId>maven-assembly-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>distribution-package</id>
+ <phase>package</phase>
+ <goals>
+ <goal>single</goal>
+ </goals>
+ <configuration>
+ <descriptors>
+ <descriptor>src/main/assembly/systests.xml</descriptor>
+ </descriptors>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+
+ </build>
+
+</project>
diff --git a/java/systests/distribution/src/main/assembly/systests.xml b/java/systests/distribution/src/main/assembly/systests.xml
new file mode 100644
index 0000000000..2d6a6d8572
--- /dev/null
+++ b/java/systests/distribution/src/main/assembly/systests.xml
@@ -0,0 +1,91 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ * 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.
+-->
+<assembly>
+ <id>system-test-java</id>
+ <includeBaseDirectory>false</includeBaseDirectory>
+ <formats>
+ <format>tar.gz</format>
+ <format>zip</format>
+ </formats>
+
+<fileSets>
+ <!-- Apache Licensing Details-->
+ <fileSet>
+ <directory>../../resources</directory>
+ <outputDirectory>qpid-${qpid.version}</outputDirectory>
+ <includes>
+ <include>DISCLAIMER</include>
+ <include>LICENSE.txt</include>
+ <include>NOTICE.txt</include>
+ <include>README.txt</include>
+ </includes>
+ </fileSet>
+ <fileSet>
+ <directory>..</directory>
+ <outputDirectory>qpid-${qpid.version}</outputDirectory>
+ <includes>
+ <include>*.txt</include>
+ </includes>
+ </fileSet>
+ <fileSet>
+ <directory>../../release-docs</directory>
+ <outputDirectory>qpid-${qpid.version}/docs</outputDirectory>
+ <includes>
+ <include>RELEASE_NOTES.txt</include>
+ </includes>
+ </fileSet>
+
+ <!-- Scripts to run the system tests-->
+ <fileSet>
+ <directory>../bin</directory>
+ <outputDirectory>qpid-${qpid.version}/bin</outputDirectory>
+ <includes>
+ <include>*</include>
+ </includes>
+ </fileSet>
+
+ <!-- Include source files in easy access form -->
+ <fileSet>
+ <directory>../src/main</directory>
+ <outputDirectory>qpid-${qpid.version}/src</outputDirectory>
+ <includes>
+ <include>**/*.java</include>
+ <include>**/*.log4j</include>
+ </includes>
+ </fileSet>
+ <fileSet>
+ <directory>target</directory>
+ <outputDirectory>qpid-${qpid.version}/lib</outputDirectory>
+ <includes>
+ <include>qpid-systests.jar</include>
+ </includes>
+ </fileSet>
+ </fileSets>
+
+ <dependencySets>
+ <dependencySet>
+ <outputDirectory>qpid-${qpid.version}/lib</outputDirectory>
+ <unpack>false</unpack>
+ <excludes>
+ <exclude>org.apache.qpid:qpid-systests-distribution</exclude>
+ </excludes>
+ </dependencySet>
+ </dependencySets>
+</assembly>
diff --git a/java/systests/pom.xml b/java/systests/pom.xml
index c73e5f2c44..614166754c 100644
--- a/java/systests/pom.xml
+++ b/java/systests/pom.xml
@@ -39,23 +39,20 @@
<dependencies>
<dependency>
<groupId>org.apache.qpid</groupId>
- <artifactId>qpid-common</artifactId>
- </dependency>
- <dependency>
- <groupId>org.apache.qpid</groupId>
<artifactId>qpid-client</artifactId>
+ <type>jar</type>
</dependency>
+
<dependency>
<groupId>org.apache.qpid</groupId>
<artifactId>qpid-broker</artifactId>
+ <type>jar</type>
</dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-simple</artifactId>
- </dependency>
+
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
+ <scope>compile</scope>
</dependency>
</dependencies>
@@ -65,26 +62,30 @@
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
- <systemProperties>
- <property>
- <name>amqj.noAutoCreateVMBroker</name>
- <value>true</value>
- </property>
- <property>
- <name>amqj.logging.level</name>
- <value>${amqj.logging.level}</value>
- </property>
- <property>
- <name>log4j.debug</name>
- <value>true</value>
- </property>
- <property>
- <name>log4j.configuration</name>
- <value>file:///${basedir}/src/test/java/log4j.properties</value>
- </property>
- </systemProperties>
+ <skip>true</skip>
</configuration>
</plugin>
+
</plugins>
+
+ <!-- Include source files in built jar -->
+ <resources>
+ <resource>
+ <targetPath>src/</targetPath>
+ <filtering>false</filtering>
+ <directory>src/main/java</directory>
+ <includes>
+ <include>**/*.java</include>
+ </includes>
+ </resource>
+ <resource>
+ <targetPath>src/</targetPath>
+ <filtering>false</filtering>
+ <directory>src/main/java</directory>
+ <includes>
+ <include>systests.log4j</include>
+ </includes>
+ </resource>
+ </resources>
</build>
</project>
diff --git a/java/systests/src/test/java/org/apache/qpid/server/AMQBrokerManagerMBeanTest.java b/java/systests/src/main/java/org/apache/qpid/server/AMQBrokerManagerMBeanTest.java
index 21ad1b6a7f..62dc44e23f 100644
--- a/java/systests/src/test/java/org/apache/qpid/server/AMQBrokerManagerMBeanTest.java
+++ b/java/systests/src/main/java/org/apache/qpid/server/AMQBrokerManagerMBeanTest.java
@@ -23,6 +23,8 @@ import org.apache.qpid.server.management.ManagedBroker;
import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.registry.ApplicationRegistry;
import org.apache.qpid.server.registry.IApplicationRegistry;
+import org.apache.qpid.server.virtualhost.VirtualHost;
+import org.apache.qpid.framing.AMQShortString;
public class AMQBrokerManagerMBeanTest extends TestCase
{
@@ -35,40 +37,44 @@ public class AMQBrokerManagerMBeanTest extends TestCase
String exchange2 = "testExchange2_" + System.currentTimeMillis();
String exchange3 = "testExchange3_" + System.currentTimeMillis();
- assertTrue(_exchangeRegistry.getExchange(exchange1) == null);
- assertTrue(_exchangeRegistry.getExchange(exchange2) == null);
- assertTrue(_exchangeRegistry.getExchange(exchange3) == null);
+ assertTrue(_exchangeRegistry.getExchange(new AMQShortString(exchange1)) == null);
+ assertTrue(_exchangeRegistry.getExchange(new AMQShortString(exchange2)) == null);
+ assertTrue(_exchangeRegistry.getExchange(new AMQShortString(exchange3)) == null);
- ManagedBroker mbean = new AMQBrokerManagerMBean();
+ VirtualHost vHost = ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHost("test");
+
+ ManagedBroker mbean = new AMQBrokerManagerMBean((VirtualHost.VirtualHostMBean)vHost.getManagedObject());
mbean.createNewExchange(exchange1,"direct",false, false);
mbean.createNewExchange(exchange2,"topic",false, false);
mbean.createNewExchange(exchange3,"headers",false, false);
- assertTrue(_exchangeRegistry.getExchange(exchange1) != null);
- assertTrue(_exchangeRegistry.getExchange(exchange2) != null);
- assertTrue(_exchangeRegistry.getExchange(exchange3) != null);
+ assertTrue(_exchangeRegistry.getExchange(new AMQShortString(exchange1)) != null);
+ assertTrue(_exchangeRegistry.getExchange(new AMQShortString(exchange2)) != null);
+ assertTrue(_exchangeRegistry.getExchange(new AMQShortString(exchange3)) != null);
mbean.unregisterExchange(exchange1);
mbean.unregisterExchange(exchange2);
mbean.unregisterExchange(exchange3);
- assertTrue(_exchangeRegistry.getExchange(exchange1) == null);
- assertTrue(_exchangeRegistry.getExchange(exchange2) == null);
- assertTrue(_exchangeRegistry.getExchange(exchange3) == null);
+ assertTrue(_exchangeRegistry.getExchange(new AMQShortString(exchange1)) == null);
+ assertTrue(_exchangeRegistry.getExchange(new AMQShortString(exchange2)) == null);
+ assertTrue(_exchangeRegistry.getExchange(new AMQShortString(exchange3)) == null);
}
public void testQueueOperations() throws Exception
{
String queueName = "testQueue_" + System.currentTimeMillis();
- ManagedBroker mbean = new AMQBrokerManagerMBean();
+ VirtualHost vHost = ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHost("test");
+
+ ManagedBroker mbean = new AMQBrokerManagerMBean((VirtualHost.VirtualHostMBean)vHost.getManagedObject());
- assertTrue(_queueRegistry.getQueue(queueName) == null);
+ assertTrue(_queueRegistry.getQueue(new AMQShortString(queueName)) == null);
mbean.createNewQueue(queueName, false, "test", true);
- assertTrue(_queueRegistry.getQueue(queueName) != null);
+ assertTrue(_queueRegistry.getQueue(new AMQShortString(queueName)) != null);
mbean.deleteQueue(queueName);
- assertTrue(_queueRegistry.getQueue(queueName) == null);
+ assertTrue(_queueRegistry.getQueue(new AMQShortString(queueName)) == null);
}
@Override
@@ -76,7 +82,7 @@ public class AMQBrokerManagerMBeanTest extends TestCase
{
super.setUp();
IApplicationRegistry appRegistry = ApplicationRegistry.getInstance();
- _queueRegistry = appRegistry.getQueueRegistry();
- _exchangeRegistry = appRegistry.getExchangeRegistry();
+ _queueRegistry = appRegistry.getVirtualHostRegistry().getVirtualHost("test").getQueueRegistry();
+ _exchangeRegistry = appRegistry.getVirtualHostRegistry().getVirtualHost("test").getExchangeRegistry();
}
}
diff --git a/java/systests/src/test/java/org/apache/qpid/server/ack/TxAckTest.java b/java/systests/src/main/java/org/apache/qpid/server/ack/TxAckTest.java
index 1a15ca7561..5451d64b45 100644
--- a/java/systests/src/test/java/org/apache/qpid/server/ack/TxAckTest.java
+++ b/java/systests/src/main/java/org/apache/qpid/server/ack/TxAckTest.java
@@ -7,9 +7,9 @@
* 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
@@ -20,16 +20,18 @@
*/
package org.apache.qpid.server.ack;
+import junit.framework.TestCase;
import org.apache.qpid.AMQException;
+import org.apache.qpid.framing.MessageTransferBody;
+import org.apache.qpid.server.RequiredDeliveryException;
import org.apache.qpid.server.queue.AMQMessage;
import org.apache.qpid.server.store.TestableMemoryMessageStore;
+import org.apache.qpid.server.store.StoreContext;
+import org.apache.qpid.server.store.MessageStore;
+import org.apache.qpid.server.txn.NonTransactionalContext;
+import org.apache.qpid.server.txn.TransactionalContext;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.LinkedHashMap;
-import java.util.List;
-
-import junit.framework.TestCase;
+import java.util.*;
public class TxAckTest extends TestCase
{
@@ -87,18 +89,54 @@ public class TxAckTest extends TestCase
private class Scenario
{
- private final LinkedHashMap<Long, UnacknowledgedMessage> _messages = new LinkedHashMap<Long, UnacknowledgedMessage>();
- private final UnacknowledgedMessageMap _map = new UnacknowledgedMessageMapImpl(_messages, _messages);
+ private final UnacknowledgedMessageMap _map = new UnacknowledgedMessageMapImpl(5000);
private final TxAck _op = new TxAck(_map);
private final List<Long> _acked;
private final List<Long> _unacked;
+ private StoreContext _storeContext = new StoreContext();
Scenario(int messageCount, List<Long> acked, List<Long> unacked)
{
+ MessageStore messageStore = new TestableMemoryMessageStore();
+ TransactionalContext txnContext = new NonTransactionalContext(messageStore,
+ _storeContext, null,
+ new LinkedList<RequiredDeliveryException>(),
+ new HashSet<Long>());
for(int i = 0; i < messageCount; i++)
{
long deliveryTag = i + 1;
- _messages.put(deliveryTag, new UnacknowledgedMessage(null, new TestMessage(deliveryTag), null, deliveryTag));
+ // TODO: fix hardcoded protocol version data
+ TestMessage message = new TestMessage(deliveryTag, messageStore,
+ new MessageTransferBody(
+ (byte)0,
+ (byte)9,
+ MessageTransferBody.getClazz((byte)0,(byte)9),
+ MessageTransferBody.getMethod((byte)0,(byte)9),
+ null, // AMQShortString appId
+ null, // FieldTable applicationHeaders
+ null, // Content body
+ null, // AMQShortString contentEncoding
+ null, // AMQShortString contentType
+ null, // AMQShortString correlationId
+ (short)0, // short deliveryMode
+ null, // AMQShortString destination
+ null, // AMQShortString exchange
+ 0L, // long expiration
+ false, // boolean immediate
+ false, // boolean mandatory
+ null, // AMQShortString messageId
+ (short)0, // short priority
+ false, // boolean redelivered
+ null, // AMQShortString replyTo
+ null, // AMQShortString routingKey
+ null, // byte[] securityToken
+ 0, // int ticket
+ 0L, // long timestamp
+ null, // AMQShortString transactionId
+ 0L, // long ttl
+ null), // AMQShortString userId
+ txnContext);
+ _map.add(deliveryTag, new UnacknowledgedMessage(null, message, null, deliveryTag));
}
_acked = acked;
_unacked = unacked;
@@ -113,7 +151,7 @@ public class TxAckTest extends TestCase
{
for(long tag : tags)
{
- UnacknowledgedMessage u = _messages.get(tag);
+ UnacknowledgedMessage u = _map.get(tag);
assertTrue("Message not found for tag " + tag, u != null);
((TestMessage) u.message).assertCountEquals(expected);
}
@@ -122,11 +160,11 @@ public class TxAckTest extends TestCase
void prepare() throws AMQException
{
_op.consolidate();
- _op.prepare();
+ _op.prepare(_storeContext);
assertCount(_acked, -1);
assertCount(_unacked, 0);
-
+
}
void undoPrepare()
{
@@ -140,16 +178,16 @@ public class TxAckTest extends TestCase
void commit()
{
_op.consolidate();
- _op.commit();
-
+ _op.commit(_storeContext);
+
//check acked messages are removed from map
- HashSet<Long> keys = new HashSet<Long>(_messages.keySet());
+ Set<Long> keys = new HashSet<Long>(_map.getDeliveryTags());
keys.retainAll(_acked);
assertTrue("Expected messages with following tags to have been removed from map: " + keys, keys.isEmpty());
//check unacked messages are still in map
keys = new HashSet<Long>(_unacked);
- keys.removeAll(_messages.keySet());
+ keys.removeAll(_map.getDeliveryTags());
assertTrue("Expected messages with following tags to still be in map: " + keys, keys.isEmpty());
}
}
@@ -159,9 +197,9 @@ public class TxAckTest extends TestCase
private final long _tag;
private int _count;
- TestMessage(long tag)
+ TestMessage(long tag, MessageStore store, MessageTransferBody transferBody, TransactionalContext txnContext)
{
- super(new TestableMemoryMessageStore(), null);
+ super(store, transferBody, txnContext);
_tag = tag;
}
@@ -170,7 +208,7 @@ public class TxAckTest extends TestCase
_count++;
}
- public void decrementReference()
+ public void decrementReference(StoreContext context)
{
_count--;
}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/exchange/AbstractHeadersExchangeTestBase.java b/java/systests/src/main/java/org/apache/qpid/server/exchange/AbstractHeadersExchangeTestBase.java
new file mode 100644
index 0000000000..a047afa978
--- /dev/null
+++ b/java/systests/src/main/java/org/apache/qpid/server/exchange/AbstractHeadersExchangeTestBase.java
@@ -0,0 +1,330 @@
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+package org.apache.qpid.server.exchange;
+
+import junit.framework.TestCase;
+import org.apache.qpid.AMQException;
+import org.apache.qpid.framing.*;
+import org.apache.qpid.server.queue.AMQMessage;
+import org.apache.qpid.server.queue.AMQQueue;
+import org.apache.qpid.server.queue.MessageHandleFactory;
+import org.apache.qpid.server.registry.ApplicationRegistry;
+import org.apache.qpid.server.store.MessageStore;
+import org.apache.qpid.server.store.SkeletonMessageStore;
+import org.apache.qpid.server.store.MemoryMessageStore;
+import org.apache.qpid.server.store.StoreContext;
+import org.apache.qpid.server.txn.NonTransactionalContext;
+import org.apache.qpid.server.txn.TransactionalContext;
+import org.apache.qpid.server.RequiredDeliveryException;
+import org.apache.log4j.Logger;
+
+import java.util.*;
+
+public class AbstractHeadersExchangeTestBase extends TestCase
+{
+ private static TransactionalContext txnContext = null;
+
+ private static final Logger _log = Logger.getLogger(AbstractHeadersExchangeTestBase.class);
+
+ private final HeadersExchange exchange = new HeadersExchange();
+ protected final Set<TestQueue> queues = new HashSet<TestQueue>();
+
+ /**
+ * Not used in this test, just there to stub out the routing calls
+ */
+ private MessageStore _store = new MemoryMessageStore();
+
+ private StoreContext _storeContext = new StoreContext();
+
+ private MessageHandleFactory _handleFactory = new MessageHandleFactory();
+
+ private int count;
+
+ public void testDoNothing()
+ {
+ // this is here only to make junit under Eclipse happy
+ }
+
+ protected TestQueue bindDefault(String... bindings) throws AMQException
+ {
+ return bind("Queue" + (++count), bindings);
+ }
+
+ protected TestQueue bind(String queueName, String... bindings) throws AMQException
+ {
+ return bind(queueName, getHeaders(bindings));
+ }
+
+ protected TestQueue bind(String queue, FieldTable bindings) throws AMQException
+ {
+ return bind(new TestQueue(new AMQShortString(queue)), bindings);
+ }
+
+ protected TestQueue bind(TestQueue queue, String... bindings) throws AMQException
+ {
+ return bind(queue, getHeaders(bindings));
+ }
+
+ protected TestQueue bind(TestQueue queue, FieldTable bindings) throws AMQException
+ {
+ queues.add(queue);
+ exchange.registerQueue(null, queue, bindings);
+ return queue;
+ }
+
+
+ protected void route(Message m) throws AMQException
+ {
+ m.route(exchange);
+// m.routingComplete(_store, _storeContext, _handleFactory);
+ }
+
+ protected void routeAndTest(Message m, TestQueue... expected) throws AMQException
+ {
+ routeAndTest(m, false, Arrays.asList(expected));
+ }
+
+ protected void routeAndTest(Message m, boolean expectReturn, TestQueue... expected) throws AMQException
+ {
+ routeAndTest(m, expectReturn, Arrays.asList(expected));
+ }
+
+ protected void routeAndTest(Message m, List<TestQueue> expected) throws AMQException
+ {
+ routeAndTest(m, false, expected);
+ }
+
+ protected void routeAndTest(Message m, boolean expectReturn, List<TestQueue> expected) throws AMQException
+ {
+ try
+ {
+ route(m);
+ assertFalse("Expected "+m+" to be returned due to manadatory flag, and lack of routing",expectReturn);
+ for (TestQueue q : queues)
+ {
+ if (expected.contains(q))
+ {
+ assertTrue("Expected " + m + " to be delivered to " + q, m.isInQueue(q));
+ //assert m.isInQueue(q) : "Expected " + m + " to be delivered to " + q;
+ }
+ else
+ {
+ assertFalse("Did not expect " + m + " to be delivered to " + q, m.isInQueue(q));
+ //assert !m.isInQueue(q) : "Did not expect " + m + " to be delivered to " + q;
+ }
+ }
+ }
+
+ catch (NoRouteException ex)
+ {
+ assertTrue("Expected "+m+" not to be returned",expectReturn);
+ }
+
+ }
+
+ static FieldTable getHeaders(String... entries)
+ {
+ FieldTable headers = FieldTableFactory.newFieldTable();
+ for (String s : entries)
+ {
+ String[] parts = s.split("=", 2);
+ headers.setObject(parts[0], parts.length > 1 ? parts[1] : "");
+ }
+ return headers;
+ }
+
+ static MessageTransferBody getPublishRequest(String id)
+ {
+ // AMQP version change: Hardwire the version to 0-9 (major=0, minor=9)
+ // TODO: Establish some way to determine the version for the test.
+ MessageTransferBody request = new MessageTransferBody(
+ (byte)0,
+ (byte)9,
+ MessageTransferBody.getClazz((byte)0,(byte)9),
+ MessageTransferBody.getMethod((byte)0,(byte)9),
+ new AMQShortString(id), // AMQShortString appId
+ null, // FieldTable applicationHeaders
+ null, // Content body
+ null, // AMQShortString contentEncoding
+ null, // AMQShortString contentType
+ null, // AMQShortString correlationId
+ (short)0, // short deliveryMode
+ null, // AMQShortString destination
+ null, // AMQShortString exchange
+ 0L, // long expiration
+ false, // boolean immediate
+ false, // boolean mandatory
+ null, // AMQShortString messageId
+ (short)0, // short priority
+ false, // boolean redelivered
+ null, // AMQShortString replyTo
+ null, // AMQShortString routingKey
+ null, // byte[] securityToken
+ 0, // int ticket
+ 0L, // long timestamp
+ null, // AMQShortString transactionId
+ 0L, // long ttl
+ null); // AMQShortString userId
+
+ return request;
+ }
+
+// static ContentHeaderBody getContentHeader(FieldTable headers)
+// {
+// ContentHeaderBody header = new ContentHeaderBody();
+// header.properties = getProperties(headers);
+// return header;
+// }
+//
+// static BasicContentHeaderProperties getProperties(FieldTable headers)
+// {
+// BasicContentHeaderProperties properties = new BasicContentHeaderProperties();
+// properties.setHeaders(headers);
+// return properties;
+// }
+
+ static class TestQueue extends AMQQueue
+ {
+ final List<HeadersExchangeTest.Message> messages = new ArrayList<HeadersExchangeTest.Message>();
+
+ public TestQueue(AMQShortString name) throws AMQException
+ {
+ super(name, false, new AMQShortString("test"), true, ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHost("test"));
+ }
+
+ /**
+ * We override this method so that the default behaviour, which attempts to use a delivery manager, is
+ * not invoked. It is unnecessary since for this test we only care to know whether the message was
+ * sent to the queue; the queue processing logic is not being tested.
+ * @param msg
+ * @throws AMQException
+ */
+ public void process(StoreContext context, AMQMessage msg) throws AMQException
+ {
+ messages.add(new HeadersExchangeTest.Message(msg));
+ }
+ }
+
+ /**
+ * Just add some extra utility methods to AMQMessage to aid testing.
+ */
+ static class Message extends AMQMessage
+ {
+ private static MessageStore _messageStore = new SkeletonMessageStore();
+
+ private static StoreContext _storeContext = new StoreContext();
+
+ private static TransactionalContext _txnContext = new NonTransactionalContext(_messageStore, _storeContext,
+ null,
+ new LinkedList<RequiredDeliveryException>(),
+ new HashSet<Long>());
+
+ Message(String id, String... headers) throws AMQException
+ {
+ this(new MessageTransferBody(
+ (byte)0,
+ (byte)9,
+ MessageTransferBody.getClazz((byte)0,(byte)9),
+ MessageTransferBody.getMethod((byte)0,(byte)9),
+ null, // AMQShortString appId
+ getHeaders(headers), // FieldTable applicationHeaders
+ null, // Content body
+ null, // AMQShortString contentEncoding
+ null, // AMQShortString contentType
+ null, // AMQShortString correlationId
+ (short)0, // short deliveryMode
+ null, // AMQShortString destination
+ null, // AMQShortString exchange
+ 0L, // long expiration
+ false, // boolean immediate
+ false, // boolean mandatory
+ new AMQShortString(id), // AMQShortString messageId
+ (short)0, // short priority
+ false, // boolean redelivered
+ null, // AMQShortString replyTo
+ null, // AMQShortString routingKey
+ null, // byte[] securityToken
+ 0, // int ticket
+ 0L, // long timestamp
+ null, // AMQShortString transactionId
+ 0L, // long ttl
+ null)); // AMQShortString userId
+ }
+
+// Message(String id, FieldTable headers) throws AMQException
+// {
+// this(getPublishRequest(id), getContentHeader(headers), null);
+// }
+
+ private Message(MessageTransferBody publish) throws AMQException
+ {
+ super(_messageStore, publish, _txnContext);
+ }
+
+ private Message(AMQMessage msg) throws AMQException
+ {
+ super(msg);
+ }
+
+ void route(Exchange exchange) throws AMQException
+ {
+ exchange.route(this);
+ }
+
+ boolean isInQueue(TestQueue queue)
+ {
+ return queue.messages.contains(this);
+ }
+
+ public int hashCode()
+ {
+ return getKey().hashCode();
+ }
+
+ public boolean equals(Object o)
+ {
+ return o instanceof HeadersExchangeTest.Message && equals((HeadersExchangeTest.Message) o);
+ }
+
+ private boolean equals(HeadersExchangeTest.Message m)
+ {
+ return getKey().equals(m.getKey());
+ }
+
+ public String toString()
+ {
+ return getKey().toString();
+ }
+
+ private Object getKey()
+ {
+// try
+// {
+ return getTransferBody().getRoutingKey();
+// }
+// catch (AMQException e)
+// {
+// _log.error("Error getting routing key: " + e, e);
+// return null;
+// }
+ }
+ }
+}
diff --git a/java/systests/src/test/java/org/apache/qpid/server/exchange/ExchangeMBeanTest.java b/java/systests/src/main/java/org/apache/qpid/server/exchange/ExchangeMBeanTest.java
index bb88d2e8d0..9653155a51 100644
--- a/java/systests/src/test/java/org/apache/qpid/server/exchange/ExchangeMBeanTest.java
+++ b/java/systests/src/main/java/org/apache/qpid/server/exchange/ExchangeMBeanTest.java
@@ -21,7 +21,11 @@ import junit.framework.TestCase;
import org.apache.qpid.server.queue.AMQQueue;
import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.registry.ApplicationRegistry;
+import org.apache.qpid.server.registry.IApplicationRegistry;
import org.apache.qpid.server.management.ManagedObject;
+import org.apache.qpid.server.virtualhost.VirtualHost;
+import org.apache.qpid.exchange.ExchangeDefaults;
+import org.apache.qpid.framing.AMQShortString;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.TabularData;
@@ -34,6 +38,7 @@ public class ExchangeMBeanTest extends TestCase
{
private AMQQueue _queue;
private QueueRegistry _queueRegistry;
+ private VirtualHost _virtualHost;
/**
* Test for direct exchange mbean
@@ -43,12 +48,12 @@ public class ExchangeMBeanTest extends TestCase
public void testDirectExchangeMBean() throws Exception
{
DestNameExchange exchange = new DestNameExchange();
- exchange.initialise("amq.direct", false, 0, true);
+ exchange.initialise(_virtualHost, ExchangeDefaults.DIRECT_EXCHANGE_NAME, false, 0, true);
ManagedObject managedObj = exchange.getManagedObject();
ManagedExchange mbean = (ManagedExchange)managedObj;
- mbean.createNewBinding(_queue.getName(), "binding1");
- mbean.createNewBinding(_queue.getName(), "binding2");
+ mbean.createNewBinding(_queue.getName().toString(), "binding1");
+ mbean.createNewBinding(_queue.getName().toString(), "binding2");
TabularData data = mbean.bindings();
ArrayList<CompositeData> list = new ArrayList<CompositeData>(data.values());
@@ -70,12 +75,12 @@ public class ExchangeMBeanTest extends TestCase
public void testTopicExchangeMBean() throws Exception
{
DestWildExchange exchange = new DestWildExchange();
- exchange.initialise("amq.topic", false, 0, true);
+ exchange.initialise(_virtualHost,ExchangeDefaults.TOPIC_EXCHANGE_NAME, false, 0, true);
ManagedObject managedObj = exchange.getManagedObject();
ManagedExchange mbean = (ManagedExchange)managedObj;
- mbean.createNewBinding(_queue.getName(), "binding1");
- mbean.createNewBinding(_queue.getName(), "binding2");
+ mbean.createNewBinding(_queue.getName().toString(), "binding1");
+ mbean.createNewBinding(_queue.getName().toString(), "binding2");
TabularData data = mbean.bindings();
ArrayList<CompositeData> list = new ArrayList<CompositeData>(data.values());
@@ -97,19 +102,19 @@ public class ExchangeMBeanTest extends TestCase
public void testHeadersExchangeMBean() throws Exception
{
HeadersExchange exchange = new HeadersExchange();
- exchange.initialise("amq.headers", false, 0, true);
+ exchange.initialise(_virtualHost,ExchangeDefaults.HEADERS_EXCHANGE_NAME, false, 0, true);
ManagedObject managedObj = exchange.getManagedObject();
ManagedExchange mbean = (ManagedExchange)managedObj;
- mbean.createNewBinding(_queue.getName(), "key1=binding1,key2=binding2");
- mbean.createNewBinding(_queue.getName(), "key3=binding3");
+ mbean.createNewBinding(_queue.getName().toString(), "key1=binding1,key2=binding2");
+ mbean.createNewBinding(_queue.getName().toString(), "key3=binding3");
TabularData data = mbean.bindings();
ArrayList<CompositeData> list = new ArrayList<CompositeData>(data.values());
assertTrue(list.size() == 2);
// test general exchange properties
- assertEquals(mbean.getName(), "amq.headers");
+ assertEquals(mbean.getName(), "amq.match");
assertEquals(mbean.getExchangeType(), "headers");
assertTrue(mbean.getTicketNo() == 0);
assertTrue(!mbean.isDurable());
@@ -120,8 +125,11 @@ public class ExchangeMBeanTest extends TestCase
protected void setUp() throws Exception
{
super.setUp();
- _queueRegistry = ApplicationRegistry.getInstance().getQueueRegistry();
- _queue = new AMQQueue("testQueue", false, "ExchangeMBeanTest", false, _queueRegistry);
+
+ IApplicationRegistry applicationRegistry = ApplicationRegistry.getInstance();
+ _virtualHost = applicationRegistry.getVirtualHostRegistry().getVirtualHost("test");
+ _queueRegistry = _virtualHost.getQueueRegistry();
+ _queue = new AMQQueue(new AMQShortString("testQueue"), false, new AMQShortString("ExchangeMBeanTest"), false, _virtualHost);
_queueRegistry.registerQueue(_queue);
}
}
diff --git a/java/systests/src/test/java/org/apache/qpid/server/exchange/HeadersExchangeTest.java b/java/systests/src/main/java/org/apache/qpid/server/exchange/HeadersExchangeTest.java
index 00a645628f..7bfc2e5386 100644
--- a/java/systests/src/test/java/org/apache/qpid/server/exchange/HeadersExchangeTest.java
+++ b/java/systests/src/main/java/org/apache/qpid/server/exchange/HeadersExchangeTest.java
@@ -21,16 +21,17 @@
package org.apache.qpid.server.exchange;
import org.apache.qpid.AMQException;
-import org.apache.qpid.framing.MessageTransferBody;
import org.apache.qpid.server.registry.ApplicationRegistry;
import org.apache.qpid.server.util.TestApplicationRegistry;
+import org.apache.qpid.server.util.NullApplicationRegistry;
+import org.apache.qpid.framing.MessageTransferBody;
public class HeadersExchangeTest extends AbstractHeadersExchangeTestBase
{
protected void setUp() throws Exception
{
super.setUp();
- ApplicationRegistry.initialise(new TestApplicationRegistry());
+ ApplicationRegistry.initialise(new NullApplicationRegistry());
}
public void testSimple() throws AMQException
@@ -54,14 +55,16 @@ public class HeadersExchangeTest extends AbstractHeadersExchangeTestBase
Message m7 = new Message("Message7", "XXXXX");
- MessageTransferBody tb7 = m7.getTransferBody();
- tb7.mandatory = true;
+ MessageTransferBody mtb7 = m7.getTransferBody();
+ mtb7.mandatory = true;
routeAndTest(m7,true);
Message m8 = new Message("Message8", "F0000");
- MessageTransferBody tb8 = m8.getTransferBody();
- tb8.mandatory = true;
+ MessageTransferBody mtb8 = m8.getTransferBody();
+ mtb8.mandatory = true;
routeAndTest(m8,false,q1);
+
+
}
public void testAny() throws AMQException
@@ -85,10 +88,10 @@ public class HeadersExchangeTest extends AbstractHeadersExchangeTestBase
bindDefault("F0000");
Message m1 = new Message("Message1", "XXXXX");
Message m2 = new Message("Message2", "F0000");
- MessageTransferBody tb1 = m1.getTransferBody();
- tb1.mandatory = true;
- MessageTransferBody tb2 = m2.getTransferBody();
- tb2.mandatory = true;
+ MessageTransferBody mtb1 = m1.getTransferBody();
+ mtb1.mandatory = true;
+ MessageTransferBody mtb2 = m2.getTransferBody();
+ mtb2.mandatory = true;
routeAndTest(m1,true);
}
diff --git a/java/systests/src/test/java/org/apache/qpid/server/exchange/ReturnUnroutableMandatoryMessageTest.java b/java/systests/src/main/java/org/apache/qpid/server/exchange/ReturnUnroutableMandatoryMessageTest.java
index 546c61eda0..c8271f1549 100644
--- a/java/systests/src/test/java/org/apache/qpid/server/exchange/ReturnUnroutableMandatoryMessageTest.java
+++ b/java/systests/src/main/java/org/apache/qpid/server/exchange/ReturnUnroutableMandatoryMessageTest.java
@@ -4,6 +4,7 @@ import junit.framework.TestCase;
import org.apache.log4j.Logger;
import org.apache.qpid.server.registry.ApplicationRegistry;
import org.apache.qpid.server.util.TestApplicationRegistry;
+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;
@@ -38,7 +39,7 @@ public class ReturnUnroutableMandatoryMessageTest extends TestCase implements Ex
{
super.setUp();
TransportConnection.createVMBroker(1);
- ApplicationRegistry.initialise(new TestApplicationRegistry(), 1);
+ ApplicationRegistry.initialise(new NullApplicationRegistry(), 1);
}
protected void tearDown() throws Exception
diff --git a/java/systests/src/test/java/org/apache/qpid/server/protocol/AMQProtocolSessionMBeanTest.java b/java/systests/src/main/java/org/apache/qpid/server/protocol/AMQProtocolSessionMBeanTest.java
index f84f14f28d..3e23b9ae42 100644
--- a/java/systests/src/test/java/org/apache/qpid/server/protocol/AMQProtocolSessionMBeanTest.java
+++ b/java/systests/src/main/java/org/apache/qpid/server/protocol/AMQProtocolSessionMBeanTest.java
@@ -21,17 +21,21 @@ import junit.framework.TestCase;
import org.apache.mina.common.IoSession;
import org.apache.qpid.codec.AMQCodecFactory;
import org.apache.qpid.server.AMQChannel;
+import org.apache.qpid.server.virtualhost.VirtualHost;
+import org.apache.qpid.server.registry.IApplicationRegistry;
+import org.apache.qpid.server.registry.ApplicationRegistry;
import org.apache.qpid.server.exchange.DefaultExchangeFactory;
import org.apache.qpid.server.exchange.DefaultExchangeRegistry;
import org.apache.qpid.server.exchange.ExchangeRegistry;
import org.apache.qpid.server.queue.DefaultQueueRegistry;
import org.apache.qpid.server.queue.QueueRegistry;
+import org.apache.qpid.server.queue.AMQQueue;
import org.apache.qpid.server.store.MessageStore;
import org.apache.qpid.server.store.SkeletonMessageStore;
import org.apache.qpid.AMQException;
+import org.apache.qpid.framing.AMQShortString;
import javax.management.JMException;
-import javax.management.openmbean.OpenDataException;
/**
* Test class to test MBean operations for AMQMinaProtocolSession.
@@ -45,23 +49,28 @@ public class AMQProtocolSessionMBeanTest extends TestCase
private QueueRegistry _queueRegistry;
private ExchangeRegistry _exchangeRegistry;
private AMQProtocolSessionMBean _mbean;
+ private VirtualHost _virtualHost;
public void testChannels() throws Exception
{
// check the channel count is correct
int channelCount = _mbean.channels().size();
- assertTrue(channelCount == 2);
- _protocolSession.addChannel(new AMQChannel(2,_protocolSession, _messageStore, null,null));
+ assertTrue(channelCount == 1);
+ AMQQueue queue = new org.apache.qpid.server.queue.AMQQueue(new AMQShortString("testQueue_" + System.currentTimeMillis()),
+ false, new AMQShortString("test"), true, _virtualHost);
+ AMQChannel channel = new AMQChannel(2, _protocolSession, _virtualHost.getMessageStore(), _virtualHost.getExchangeRegistry(), null/*methodListener*/);
+ channel.setDefaultQueue(queue);
+ _protocolSession.addChannel(channel);
channelCount = _mbean.channels().size();
- assertTrue(channelCount == 3);
+ assertTrue(channelCount == 2);
// general properties test
_mbean.setMaximumNumberOfChannels(1000L);
assertTrue(_mbean.getMaximumNumberOfChannels() == 1000L);
// check APIs
- AMQChannel channel3 = new AMQChannel(3,_protocolSession, _messageStore, null,null);
- channel3.setTransactional(true);
+ AMQChannel channel3 = new AMQChannel(3, _protocolSession, _virtualHost.getMessageStore(), _virtualHost.getExchangeRegistry(), null/*methodListener*/);
+ channel3.setLocalTransactional();
_protocolSession.addChannel(channel3);
_mbean.rollbackTransactions(2);
_mbean.rollbackTransactions(3);
@@ -80,31 +89,33 @@ public class AMQProtocolSessionMBeanTest extends TestCase
}
// check if closing of session works
- _protocolSession.addChannel(new AMQChannel(5,_protocolSession, _messageStore, null,null));
+ _protocolSession.addChannel(new AMQChannel(5, _protocolSession, _virtualHost.getMessageStore(), _virtualHost.getExchangeRegistry(), null/*methodListener*/));
_mbean.closeConnection();
- channelCount = _mbean.channels().size();
- assertTrue(channelCount == 0);
- try
- {
+// try
+// {
+ channelCount = _mbean.channels().size();
+ assertTrue(channelCount == 0);
// session is now closed so adding another channel should throw an exception
- _protocolSession.addChannel(new AMQChannel(6,_protocolSession, _messageStore, null,null));
+ _protocolSession.addChannel(new AMQChannel(6, _protocolSession, _virtualHost.getMessageStore(), _virtualHost.getExchangeRegistry(), null/*methodListener*/));
fail();
- }
- catch(IllegalStateException ex)
- {
- System.out.println("expected exception is thrown :" + ex.getMessage());
- }
+// }
+// catch(AMQException ex)
+// {
+// System.out.println("expected exception is thrown :" + ex.getMessage());
+// }
}
@Override
protected void setUp() throws Exception
{
- super.setUp();
- _queueRegistry = new DefaultQueueRegistry();
- _exchangeRegistry = new DefaultExchangeRegistry(new DefaultExchangeFactory());
+ super.setUp();
+ _channel = new AMQChannel(1, _protocolSession, _virtualHost.getMessageStore(), _virtualHost.getExchangeRegistry(), null/*methodListener*/);
+ IApplicationRegistry appRegistry = ApplicationRegistry.getInstance();
+ _virtualHost = appRegistry.getVirtualHostRegistry().getVirtualHost("test");
+ _queueRegistry = _virtualHost.getQueueRegistry();
+ _exchangeRegistry = _virtualHost.getExchangeRegistry();
_mockIOSession = new MockIoSession();
- _protocolSession = new AMQMinaProtocolSession(_mockIOSession, _queueRegistry, _exchangeRegistry, new AMQCodecFactory(true));
- _channel = new AMQChannel(1,_protocolSession, _messageStore, null,null);
+ _protocolSession = new AMQMinaProtocolSession(_mockIOSession, appRegistry.getVirtualHostRegistry(), new AMQCodecFactory(true));
_protocolSession.addChannel(_channel);
_mbean = (AMQProtocolSessionMBean)_protocolSession.getManagedObject();
}
diff --git a/java/systests/src/test/java/org/apache/qpid/server/protocol/MockIoSession.java b/java/systests/src/main/java/org/apache/qpid/server/protocol/MockIoSession.java
index cf6366b513..cf6366b513 100644
--- a/java/systests/src/test/java/org/apache/qpid/server/protocol/MockIoSession.java
+++ b/java/systests/src/main/java/org/apache/qpid/server/protocol/MockIoSession.java
diff --git a/java/systests/src/test/java/org/apache/qpid/server/queue/AMQQueueMBeanTest.java b/java/systests/src/main/java/org/apache/qpid/server/queue/AMQQueueMBeanTest.java
index ae398961be..92ba9db728 100644
--- a/java/systests/src/test/java/org/apache/qpid/server/queue/AMQQueueMBeanTest.java
+++ b/java/systests/src/main/java/org/apache/qpid/server/queue/AMQQueueMBeanTest.java
@@ -17,20 +17,24 @@
*/
package org.apache.qpid.server.queue;
-import java.util.Collections;
-
-import javax.management.JMException;
-
import junit.framework.TestCase;
-
-import org.apache.mina.common.ByteBuffer;
import org.apache.qpid.AMQException;
-import org.apache.qpid.client.message.MessageHeaders;
-import org.apache.qpid.framing.Content;
import org.apache.qpid.framing.MessageTransferBody;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.server.AMQChannel;
+import org.apache.qpid.server.RequiredDeliveryException;
+import org.apache.qpid.server.virtualhost.VirtualHost;
+import org.apache.qpid.server.registry.IApplicationRegistry;
+import org.apache.qpid.server.registry.ApplicationRegistry;
+import org.apache.qpid.server.txn.TransactionalContext;
+import org.apache.qpid.server.txn.NonTransactionalContext;
import org.apache.qpid.server.store.MessageStore;
import org.apache.qpid.server.store.SkeletonMessageStore;
+import org.apache.qpid.server.store.StoreContext;
+
+import javax.management.JMException;
+import java.util.LinkedList;
+import java.util.HashSet;
/**
* Test class to test AMQQueueMBean attribtues and operations
@@ -41,8 +45,14 @@ public class AMQQueueMBeanTest extends TestCase
private AMQQueueMBean _queueMBean;
private QueueRegistry _queueRegistry;
private MessageStore _messageStore = new SkeletonMessageStore();
+ private StoreContext _storeContext = new StoreContext();
+ private TransactionalContext _transactionalContext = new NonTransactionalContext(_messageStore, _storeContext,
+ null,
+ new LinkedList<RequiredDeliveryException>(),
+ new HashSet<Long>());
private MockProtocolSession _protocolSession;
private AMQChannel _channel;
+ private VirtualHost _virtualHost;
public void testMessageCount() throws Exception
{
@@ -50,8 +60,7 @@ public class AMQQueueMBeanTest extends TestCase
sendMessages(messageCount);
assertTrue(_queueMBean.getMessageCount() == messageCount);
assertTrue(_queueMBean.getReceivedMessageCount() == messageCount);
- // each message is 1K
- assertTrue(_queueMBean.getQueueDepth() == messageCount);
+ assertTrue(_queueMBean.getQueueDepth() == 10);
_queueMBean.deleteMessageFromTop();
assertTrue(_queueMBean.getMessageCount() == messageCount - 1);
@@ -67,12 +76,12 @@ public class AMQQueueMBeanTest extends TestCase
SubscriptionManager mgr = _queue.getSubscribers();
assertFalse(mgr.hasActiveSubscribers());
assertTrue(_queueMBean.getActiveConsumerCount() == 0);
-
- _protocolSession = new MockProtocolSession(_messageStore);
- _channel = new AMQChannel(1,_protocolSession, _messageStore, null,null);
+
+ _channel = new AMQChannel(1, _protocolSession, _virtualHost.getMessageStore(), _virtualHost.getExchangeRegistry(), null/*methodListener*/);
+ _protocolSession = new MockProtocolSession(_messageStore);
_protocolSession.addChannel(_channel);
-
- _queue.registerProtocolSession(_protocolSession, 1, "test", false, null, false, false);
+
+ _queue.registerProtocolSession(_protocolSession, 1, new AMQShortString("test"), false, null,false,false);
assertTrue(_queueMBean.getActiveConsumerCount() == 1);
SubscriptionSet _subscribers = (SubscriptionSet) mgr;
@@ -138,8 +147,9 @@ public class AMQQueueMBeanTest extends TestCase
AMQMessage msg = message(false);
long id = msg.getMessageId();
- _queue.clearQueue();
- _queue.deliver(msg);
+ _queue.clearQueue(_storeContext);
+ _queue.process(_storeContext, msg);
+// msg.routingComplete(_messageStore, _storeContext, new MessageHandleFactory());
_queueMBean.viewMessageContent(id);
try
{
@@ -156,46 +166,46 @@ public class AMQQueueMBeanTest extends TestCase
{
// AMQP version change: Hardwire the version to 0-9 (major=0, minor=9)
// TODO: Establish some way to determine the version for the test.
-
- MessageHeaders messageHeaders = new MessageHeaders();
-
- ByteBuffer buffer = ByteBuffer.wrap(new byte[1000]);
- Content body = new Content(Content.TypeEnum.INLINE_T, buffer);
- MessageTransferBody methodBody = MessageTransferBody.createMethodBody(
- (byte)0, (byte)9, // AMQP version (major, minor)
- messageHeaders.getAppId(), // String appId
- messageHeaders.getJMSHeaders(), // FieldTable applicationHeaders
- body, // Content body
- messageHeaders.getEncoding(), // String contentEncoding
- messageHeaders.getContentType(), // String contentType
- messageHeaders.getCorrelationId(), // String correlationId
- (short)1, // short deliveryMode
- "someExchange", // String destination
- "someExchange", // String exchange
- messageHeaders.getExpiration(), // long expiration
- immediate, // boolean immediate
- false, // boolean mandatory
- "", // String messageId
- (short)0, // short priority
- false, // boolean redelivered
- messageHeaders.getReplyTo(), // String replyTo
- "rk", // String routingKey
- new String("abc123").getBytes(), // byte[] securityToken
- 0, // int ticket
- messageHeaders.getTimestamp(), // long timestamp
- messageHeaders.getTransactionId(), // String transactionId
- 0, // long ttl
- messageHeaders.getUserId()); // String userId
-
- return new AMQMessage(_messageStore, methodBody, Collections.singletonList(buffer));
+ MessageTransferBody publish = new MessageTransferBody(
+ (byte)0,
+ (byte)9,
+ MessageTransferBody.getClazz((byte)0,(byte)9),
+ MessageTransferBody.getMethod((byte)0,(byte)9),
+ null, // AMQShortString appId
+ null, // FieldTable applicationHeaders
+ null, // Content body
+ null, // AMQShortString contentEncoding
+ null, // AMQShortString contentType
+ null, // AMQShortString correlationId
+ (short)0, // short deliveryMode
+ null, // AMQShortString destination
+ null, // AMQShortString exchange
+ 0L, // long expiration
+ immediate, // boolean immediate
+ false, // boolean mandatory
+ null, // AMQShortString messageId
+ (short)0, // short priority
+ false, // boolean redelivered
+ null, // AMQShortString replyTo
+ null, // AMQShortString routingKey
+ null, // byte[] securityToken
+ 0, // int ticket
+ 0L, // long timestamp
+ null, // AMQShortString transactionId
+ 0L, // long ttl
+ null); // AMQShortString userId
+
+ return new AMQMessage(_messageStore, publish, _transactionalContext);
}
@Override
protected void setUp() throws Exception
{
super.setUp();
- _queueRegistry = new DefaultQueueRegistry();
- _queue = new AMQQueue("testQueue", false, "AMQueueMBeanTest", false, _queueRegistry);
+ IApplicationRegistry applicationRegistry = ApplicationRegistry.getInstance();
+ _virtualHost = applicationRegistry.getVirtualHostRegistry().getVirtualHost("test");
+ _queueRegistry = _virtualHost.getQueueRegistry();
+ _queue = new AMQQueue(new AMQShortString("testQueue"), false, new AMQShortString("AMQueueMBeanTest"), false, _virtualHost);
_queueMBean = new AMQQueueMBean(_queue);
}
@@ -205,11 +215,15 @@ public class AMQQueueMBeanTest extends TestCase
for (int i = 0; i < messages.length; i++)
{
messages[i] = message(false);
- ;
}
for (int i = 0; i < messageCount; i++)
{
- _queue.deliver(messages[i]);
+ _queue.process(_storeContext, messages[i]);
+ }
+
+ for (int i = 0; i < messages.length; i++)
+ {
+// messages[i].routingComplete(_messageStore, _storeContext, new MessageHandleFactory());
}
}
}
diff --git a/java/systests/src/test/java/org/apache/qpid/server/queue/AckTest.java b/java/systests/src/main/java/org/apache/qpid/server/queue/AckTest.java
index ca777ca535..a812257203 100644
--- a/java/systests/src/test/java/org/apache/qpid/server/queue/AckTest.java
+++ b/java/systests/src/main/java/org/apache/qpid/server/queue/AckTest.java
@@ -7,9 +7,9 @@
* 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
@@ -20,28 +20,34 @@
*/
package org.apache.qpid.server.queue;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.Map;
-
import junit.framework.TestCase;
-
import org.apache.log4j.Logger;
import org.apache.qpid.AMQException;
-import org.apache.qpid.client.message.MessageHeaders;
-import org.apache.qpid.framing.Content;
import org.apache.qpid.framing.MessageTransferBody;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.server.AMQChannel;
+import org.apache.qpid.server.RequiredDeliveryException;
import org.apache.qpid.server.ack.UnacknowledgedMessage;
+import org.apache.qpid.server.ack.UnacknowledgedMessageMap;
import org.apache.qpid.server.registry.ApplicationRegistry;
import org.apache.qpid.server.store.TestableMemoryMessageStore;
+import org.apache.qpid.server.store.StoreContext;
+import org.apache.qpid.server.txn.NonTransactionalContext;
+import org.apache.qpid.server.txn.TransactionalContext;
import org.apache.qpid.server.util.TestApplicationRegistry;
+import org.apache.qpid.server.util.NullApplicationRegistry;
+
+import java.util.LinkedList;
+import java.util.Set;
+import java.util.HashSet;
/**
* Tests that acknowledgements are handled correctly.
*/
public class AckTest extends TestCase
{
+ private TransactionalContext txnContext = null;
+
private static final Logger _log = Logger.getLogger(AckTest.class);
private SubscriptionImpl _subscription;
@@ -50,26 +56,30 @@ public class AckTest extends TestCase
private TestableMemoryMessageStore _messageStore;
+ private StoreContext _storeContext = new StoreContext();
+
private AMQChannel _channel;
private SubscriptionSet _subscriptionManager;
private AMQQueue _queue;
+ private static final AMQShortString DEFAULT_CONSUMER_TAG = new AMQShortString("conTag");
+
public AckTest() throws Exception
{
- ApplicationRegistry.initialise(new TestApplicationRegistry());
+ ApplicationRegistry.initialise(new NullApplicationRegistry());
}
protected void setUp() throws Exception
{
super.setUp();
- _messageStore = new TestableMemoryMessageStore();
+ _messageStore = new TestableMemoryMessageStore();
_protocolSession = new MockProtocolSession(_messageStore);
- _channel = new AMQChannel(5,_protocolSession, _messageStore, null/*dont need exchange registry*/,null);
+ _channel = new AMQChannel(5, _protocolSession, null/*MessageStore*/, null/*ExchangeRegistry*/, null/*methodListener*/);
_protocolSession.addChannel(_channel);
- _subscriptionManager = new SubscriptionSet();
- _queue = new AMQQueue("myQ", false, "guest", true, new DefaultQueueRegistry(), _subscriptionManager);
+ _subscriptionManager = new SubscriptionSet();
+ _queue = new AMQQueue(new AMQShortString("myQ"), false, new AMQShortString("guest"), true, ApplicationRegistry.getInstance().getVirtualHostRegistry().getVirtualHost("test"), _subscriptionManager);
}
private void publishMessages(int count) throws AMQException
@@ -79,41 +89,54 @@ public class AckTest extends TestCase
private void publishMessages(int count, boolean persistent) throws AMQException
{
+ TransactionalContext txnContext = new NonTransactionalContext(_messageStore, _storeContext, null,
+ new LinkedList<RequiredDeliveryException>(),
+ new HashSet<Long>());
+ MessageHandleFactory factory = new MessageHandleFactory();
for (int i = 1; i <= count; i++)
{
// AMQP version change: Hardwire the version to 0-9 (major=0, minor=9)
// TODO: Establish some way to determine the version for the test.
- //AMQMessage(MessageStore store, MessageTransferBody transferBody, List<ByteBuffer> contents)
-
- MessageHeaders messageHeaders = new MessageHeaders();
-
- MessageTransferBody methodBody = MessageTransferBody.createMethodBody(
- (byte)0, (byte)9, // AMQP version (major, minor)
- messageHeaders.getAppId(), // String appId
- messageHeaders.getJMSHeaders(), // FieldTable applicationHeaders
- new Content(), // Content body
- messageHeaders.getEncoding(), // String contentEncoding
- messageHeaders.getContentType(), // String contentType
- messageHeaders.getCorrelationId(), // String correlationId
- persistent ? (short)2: (short)1, // short deliveryMode
- "someExchange", // String destination
- "someExchange", // String exchange
- messageHeaders.getExpiration(), // long expiration
- false, // boolean immediate
- false, // boolean mandatory
- "" + i, // String messageId
- (short)0, // short priority
- false, // boolean redelivered
- messageHeaders.getReplyTo(), // String replyTo
- "rk", // String routingKey
- new String("abc123").getBytes(), // byte[] securityToken
- 0, // int ticket
- messageHeaders.getTimestamp(), // long timestamp
- messageHeaders.getTransactionId(), // String transactionId
- 0, // long ttl
- messageHeaders.getUserId()); // String userId
-
- AMQMessage msg = new AMQMessage(_messageStore, methodBody, new ArrayList());
+ MessageTransferBody publishBody = new MessageTransferBody(
+ (byte)0,
+ (byte)9,
+ MessageTransferBody.getClazz((byte)0,(byte)9),
+ MessageTransferBody.getMethod((byte)0,(byte)9),
+ null, // AMQShortString appId
+ null, // FieldTable applicationHeaders
+ null, // Content body
+ null, // AMQShortString contentEncoding
+ null, // AMQShortString contentType
+ null, // AMQShortString correlationId
+ (short)0, // short deliveryMode
+ null, // AMQShortString destination
+ new AMQShortString("someExchange"), // AMQShortString exchange
+ 0L, // long expiration
+ false, // boolean immediate
+ false, // boolean mandatory
+ null, // AMQShortString messageId
+ (short)0, // short priority
+ false, // boolean redelivered
+ null, // AMQShortString replyTo
+ new AMQShortString("rk"), // AMQShortString routingKey
+ null, // byte[] securityToken
+ 0, // int ticket
+ 0L, // long timestamp
+ null, // AMQShortString transactionId
+ 0L, // long ttl
+ null); // AMQShortString userId
+ AMQMessage msg = new AMQMessage(_messageStore, publishBody, txnContext);
+ if (persistent)
+ {
+ //This is DeliveryMode.PERSISTENT
+ msg.setDeliveryMode((byte) 2);
+ }
+ // we increment the reference here since we are not delivering the messaging to any queues, which is where
+ // the reference is normally incremented. The test is easier to construct if we have direct access to the
+ // subscription
+ msg.incrementReference();
+// msg.routingComplete(_messageStore, _storeContext, factory);
+ // we manually send the message to the subscription
_subscription.send(msg, _queue);
}
}
@@ -124,25 +147,26 @@ public class AckTest extends TestCase
*/
public void testAckChannelAssociationTest() throws AMQException
{
- _subscription = new SubscriptionImpl(5, _protocolSession, "conTag", true);
+ _subscription = new SubscriptionImpl(5, _protocolSession, DEFAULT_CONSUMER_TAG, true);
final int msgCount = 10;
publishMessages(msgCount, true);
- Map<Long, UnacknowledgedMessage> map = _channel.getUnacknowledgedMessageMap();
+ UnacknowledgedMessageMap map = _channel.getUnacknowledgedMessageMap();
assertTrue(map.size() == msgCount);
- assertTrue(_messageStore.getMessageMap().size() == msgCount);
+ assertTrue(_messageStore.getMessageMetaDataMap().size() == msgCount);
- Iterator<Map.Entry<Long, UnacknowledgedMessage>> it = map.entrySet().iterator();
- for (int i = 1; i <= map.size(); i++)
+ Set<Long> deliveryTagSet = map.getDeliveryTags();
+ int i = 1;
+ for (long deliveryTag : deliveryTagSet)
{
- Map.Entry<Long, UnacknowledgedMessage> entry = it.next();
- assertTrue(entry.getKey() == i);
- UnacknowledgedMessage unackedMsg = entry.getValue();
+ assertTrue(deliveryTag == i);
+ i++;
+ UnacknowledgedMessage unackedMsg = map.get(deliveryTag);
assertTrue(unackedMsg.queue == _queue);
}
assertTrue(map.size() == msgCount);
- assertTrue(_messageStore.getMessageMap().size() == msgCount);
+ assertTrue(_messageStore.getMessageMetaDataMap().size() == msgCount);
}
/**
@@ -151,13 +175,13 @@ public class AckTest extends TestCase
public void testNoAckMode() throws AMQException
{
// false arg means no acks expected
- _subscription = new SubscriptionImpl(5, _protocolSession, "conTag", false);
+ _subscription = new SubscriptionImpl(5, _protocolSession, DEFAULT_CONSUMER_TAG, false);
final int msgCount = 10;
publishMessages(msgCount);
- Map<Long, UnacknowledgedMessage> map = _channel.getUnacknowledgedMessageMap();
+ UnacknowledgedMessageMap map = _channel.getUnacknowledgedMessageMap();
assertTrue(map.size() == 0);
- assertTrue(_messageStore.getMessageMap().size() == 0);
+ assertTrue(_messageStore.getMessageMetaDataMap().size() == 0);
}
/**
@@ -166,21 +190,20 @@ public class AckTest extends TestCase
*/
public void testSingleAckReceivedTest() throws AMQException
{
- _subscription = new SubscriptionImpl(5, _protocolSession, "conTag", true);
+ _subscription = new SubscriptionImpl(5, _protocolSession, DEFAULT_CONSUMER_TAG, true);
final int msgCount = 10;
publishMessages(msgCount);
_channel.acknowledgeMessage(5, false);
- Map<Long, UnacknowledgedMessage> map = _channel.getUnacknowledgedMessageMap();
+ UnacknowledgedMessageMap map = _channel.getUnacknowledgedMessageMap();
assertTrue(map.size() == msgCount - 1);
- Iterator<Map.Entry<Long, UnacknowledgedMessage>> it = map.entrySet().iterator();
+ Set<Long> deliveryTagSet = map.getDeliveryTags();
int i = 1;
- while (i <= map.size())
+ for (long deliveryTag : deliveryTagSet)
{
- Map.Entry<Long, UnacknowledgedMessage> entry = it.next();
- assertTrue(entry.getKey() == i);
- UnacknowledgedMessage unackedMsg = entry.getValue();
+ assertTrue(deliveryTag == i);
+ UnacknowledgedMessage unackedMsg = map.get(deliveryTag);
assertTrue(unackedMsg.queue == _queue);
// 5 is the delivery tag of the message that *should* be removed
if (++i == 5)
@@ -196,21 +219,20 @@ public class AckTest extends TestCase
*/
public void testMultiAckReceivedTest() throws AMQException
{
- _subscription = new SubscriptionImpl(5, _protocolSession, "conTag", true);
+ _subscription = new SubscriptionImpl(5, _protocolSession, DEFAULT_CONSUMER_TAG, true);
final int msgCount = 10;
publishMessages(msgCount);
_channel.acknowledgeMessage(5, true);
- Map<Long, UnacknowledgedMessage> map = _channel.getUnacknowledgedMessageMap();
+ UnacknowledgedMessageMap map = _channel.getUnacknowledgedMessageMap();
assertTrue(map.size() == 5);
- Iterator<Map.Entry<Long, UnacknowledgedMessage>> it = map.entrySet().iterator();
+ Set<Long> deliveryTagSet = map.getDeliveryTags();
int i = 1;
- while (i <= map.size())
+ for (long deliveryTag : deliveryTagSet)
{
- Map.Entry<Long, UnacknowledgedMessage> entry = it.next();
- assertTrue(entry.getKey() == i + 5);
- UnacknowledgedMessage unackedMsg = entry.getValue();
+ assertTrue(deliveryTag == i + 5);
+ UnacknowledgedMessage unackedMsg = map.get(deliveryTag);
assertTrue(unackedMsg.queue == _queue);
++i;
}
@@ -221,21 +243,20 @@ public class AckTest extends TestCase
*/
public void testMultiAckAllReceivedTest() throws AMQException
{
- _subscription = new SubscriptionImpl(5, _protocolSession, "conTag", true);
+ _subscription = new SubscriptionImpl(5, _protocolSession, DEFAULT_CONSUMER_TAG, true);
final int msgCount = 10;
publishMessages(msgCount);
_channel.acknowledgeMessage(0, true);
- Map<Long, UnacknowledgedMessage> map = _channel.getUnacknowledgedMessageMap();
+ UnacknowledgedMessageMap map = _channel.getUnacknowledgedMessageMap();
assertTrue(map.size() == 0);
- Iterator<Map.Entry<Long, UnacknowledgedMessage>> it = map.entrySet().iterator();
+ Set<Long> deliveryTagSet = map.getDeliveryTags();
int i = 1;
- while (i <= map.size())
+ for (long deliveryTag : deliveryTagSet)
{
- Map.Entry<Long, UnacknowledgedMessage> entry = it.next();
- assertTrue(entry.getKey() == i + 5);
- UnacknowledgedMessage unackedMsg = entry.getValue();
+ assertTrue(deliveryTag == i + 5);
+ UnacknowledgedMessage unackedMsg = map.get(deliveryTag);
assertTrue(unackedMsg.queue == _queue);
++i;
}
@@ -246,7 +267,7 @@ public class AckTest extends TestCase
int lowMark = 5;
int highMark = 10;
- _subscription = new SubscriptionImpl(5, _protocolSession, "conTag", true);
+ _subscription = new SubscriptionImpl(5, _protocolSession, DEFAULT_CONSUMER_TAG, true);
_channel.setPrefetchLowMarkCount(lowMark);
_channel.setPrefetchHighMarkCount(highMark);
@@ -259,7 +280,7 @@ public class AckTest extends TestCase
// which have not bee received so will be queued up in the channel
// which should be suspended
assertTrue(_subscription.isSuspended());
- Map<Long, UnacknowledgedMessage> map = _channel.getUnacknowledgedMessageMap();
+ UnacknowledgedMessageMap map = _channel.getUnacknowledgedMessageMap();
assertTrue(map.size() == highMark);
//acknowledge messages so we are just above lowMark
@@ -297,7 +318,7 @@ public class AckTest extends TestCase
public void testPrefetch() throws AMQException
{
- _subscription = new SubscriptionImpl(5, _protocolSession, "conTag", true);
+ _subscription = new SubscriptionImpl(5, _protocolSession, DEFAULT_CONSUMER_TAG, true);
_channel.setPrefetchCount(5);
assertTrue(_channel.getPrefetchCount() == 5);
@@ -308,7 +329,7 @@ public class AckTest extends TestCase
// at this point we should have sent out only 5 messages with a further 5 queued
// up in the channel which should now be suspended
assertTrue(_subscription.isSuspended());
- Map<Long, UnacknowledgedMessage> map = _channel.getUnacknowledgedMessageMap();
+ UnacknowledgedMessageMap map = _channel.getUnacknowledgedMessageMap();
assertTrue(map.size() == 5);
_channel.acknowledgeMessage(5, true);
assertTrue(!_subscription.isSuspended());
diff --git a/java/systests/src/test/java/org/apache/qpid/server/queue/ConcurrencyTest.java b/java/systests/src/main/java/org/apache/qpid/server/queue/ConcurrencyTest.java
index fe8960c872..6f3d42d090 100644
--- a/java/systests/src/test/java/org/apache/qpid/server/queue/ConcurrencyTest.java
+++ b/java/systests/src/main/java/org/apache/qpid/server/queue/ConcurrencyTest.java
@@ -7,9 +7,9 @@
* 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
@@ -21,7 +21,11 @@
package org.apache.qpid.server.queue;
import org.apache.qpid.AMQException;
+import org.apache.qpid.framing.AMQShortString;
import org.apache.qpid.server.handler.OnCurrentThreadExecutor;
+import org.apache.qpid.server.registry.IApplicationRegistry;
+import org.apache.qpid.server.registry.ApplicationRegistry;
+import org.apache.qpid.server.virtualhost.VirtualHost;
import java.util.*;
import java.util.concurrent.Executor;
@@ -49,11 +53,15 @@ public class ConcurrencyTest extends MessageTestHelper
private boolean isComplete;
private boolean failed;
+ private VirtualHost _virtualHost;
public ConcurrencyTest() throws Exception
{
- _deliveryMgr = new ConcurrentDeliveryManager(_subscriptionMgr, new AMQQueue("myQ", false, "guest", false,
- new DefaultQueueRegistry()));
+
+ IApplicationRegistry applicationRegistry = ApplicationRegistry.getInstance();
+ _virtualHost = applicationRegistry.getVirtualHostRegistry().getVirtualHost("test");
+ _deliveryMgr = new ConcurrentSelectorDeliveryManager(_subscriptionMgr, new AMQQueue(new AMQShortString("myQ"), false, new AMQShortString("guest"), false,
+ _virtualHost));
}
public void testConcurrent1() throws InterruptedException, AMQException
@@ -186,7 +194,7 @@ public class ConcurrencyTest extends MessageTestHelper
AMQMessage msg = nextMessage();
if (msg != null)
{
- _deliveryMgr.deliver(toString(), msg);
+ _deliveryMgr.deliver(null, new AMQShortString(toString()), msg);
}
}
}
diff --git a/java/systests/src/test/java/org/apache/qpid/server/queue/DeliveryManagerTest.java b/java/systests/src/main/java/org/apache/qpid/server/queue/DeliveryManagerTest.java
index 3631264e5a..e1be640c8e 100644
--- a/java/systests/src/test/java/org/apache/qpid/server/queue/DeliveryManagerTest.java
+++ b/java/systests/src/main/java/org/apache/qpid/server/queue/DeliveryManagerTest.java
@@ -7,9 +7,9 @@
* 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
@@ -21,7 +21,9 @@
package org.apache.qpid.server.queue;
import org.apache.qpid.server.handler.OnCurrentThreadExecutor;
+import org.apache.qpid.server.store.StoreContext;
import org.apache.qpid.AMQException;
+import org.apache.qpid.framing.AMQShortString;
import junit.framework.TestSuite;
@@ -29,6 +31,8 @@ abstract public class DeliveryManagerTest extends MessageTestHelper
{
protected final SubscriptionSet _subscriptions = new SubscriptionSet();
protected DeliveryManager _mgr;
+ protected StoreContext _storeContext = new StoreContext();
+ private static final AMQShortString DEFAULT_QUEUE_NAME = new AMQShortString("Me");
public DeliveryManagerTest() throws Exception
{
@@ -45,7 +49,7 @@ abstract public class DeliveryManagerTest extends MessageTestHelper
for (int i = 0; i < batch; i++)
{
- _mgr.deliver("Me", messages[i]);
+ _mgr.deliver(_storeContext, DEFAULT_QUEUE_NAME, messages[i]);
}
SubscriptionTestHelper s1 = new SubscriptionTestHelper("1");
@@ -55,7 +59,7 @@ abstract public class DeliveryManagerTest extends MessageTestHelper
for (int i = batch; i < messages.length; i++)
{
- _mgr.deliver("Me", messages[i]);
+ _mgr.deliver(_storeContext, DEFAULT_QUEUE_NAME, messages[i]);
}
assertTrue(s1.getMessages().isEmpty());
@@ -93,7 +97,7 @@ abstract public class DeliveryManagerTest extends MessageTestHelper
for (int i = 0; i < batch; i++)
{
- _mgr.deliver("Me", messages[i]);
+ _mgr.deliver(_storeContext, DEFAULT_QUEUE_NAME, messages[i]);
}
assertEquals(batch, s1.getMessages().size());
@@ -107,7 +111,7 @@ abstract public class DeliveryManagerTest extends MessageTestHelper
s1.setSuspended(true);
for (int i = batch; i < messages.length; i++)
{
- _mgr.deliver("Me", messages[i]);
+ _mgr.deliver(_storeContext, DEFAULT_QUEUE_NAME, messages[i]);
}
_mgr.processAsync(new OnCurrentThreadExecutor());
@@ -129,7 +133,7 @@ abstract public class DeliveryManagerTest extends MessageTestHelper
try
{
AMQMessage msg = message(true);
- _mgr.deliver("Me", msg);
+ _mgr.deliver(_storeContext, DEFAULT_QUEUE_NAME, msg);
msg.checkDeliveredToConsumer();
fail("expected exception did not occur");
}
@@ -151,7 +155,7 @@ abstract public class DeliveryManagerTest extends MessageTestHelper
_subscriptions.addSubscriber(s);
s.setSuspended(true);
AMQMessage msg = message(true);
- _mgr.deliver("Me", msg);
+ _mgr.deliver(_storeContext, DEFAULT_QUEUE_NAME, msg);
msg.checkDeliveredToConsumer();
fail("expected exception did not occur");
}
@@ -168,8 +172,6 @@ abstract public class DeliveryManagerTest extends MessageTestHelper
public static junit.framework.Test suite()
{
TestSuite suite = new TestSuite();
- suite.addTestSuite(ConcurrentDeliveryManagerTest.class);
- suite.addTestSuite(SynchronizedDeliveryManagerTest.class);
return suite;
}
}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/queue/MessageTestHelper.java b/java/systests/src/main/java/org/apache/qpid/server/queue/MessageTestHelper.java
new file mode 100644
index 0000000000..78f8223733
--- /dev/null
+++ b/java/systests/src/main/java/org/apache/qpid/server/queue/MessageTestHelper.java
@@ -0,0 +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.server.queue;
+
+import org.apache.qpid.framing.MessageTransferBody;
+import org.apache.qpid.server.store.MessageStore;
+import org.apache.qpid.server.store.SkeletonMessageStore;
+import org.apache.qpid.server.store.StoreContext;
+import org.apache.qpid.server.registry.ApplicationRegistry;
+import org.apache.qpid.server.util.TestApplicationRegistry;
+import org.apache.qpid.server.txn.TransactionalContext;
+import org.apache.qpid.server.txn.NonTransactionalContext;
+import org.apache.qpid.server.RequiredDeliveryException;
+import org.apache.qpid.AMQException;
+
+import junit.framework.TestCase;
+
+import java.util.LinkedList;
+import java.util.HashSet;
+
+class MessageTestHelper extends TestCase
+{
+ private final MessageStore _messageStore = new SkeletonMessageStore();
+
+ private final StoreContext _storeContext = new StoreContext();
+
+ private final TransactionalContext _txnContext = new NonTransactionalContext(_messageStore, _storeContext, null,
+ new LinkedList<RequiredDeliveryException>(),
+ new HashSet<Long>());
+
+ MessageTestHelper() throws Exception
+ {
+ ApplicationRegistry.initialise(new TestApplicationRegistry());
+ }
+
+ AMQMessage message() throws AMQException
+ {
+ return message(false);
+ }
+
+ AMQMessage message(boolean immediate) throws AMQException
+ {
+ // AMQP version change: Hardwire the version to 0-8 (major=8, minor=0)
+ // TODO: Establish some way to determine the version for the test.
+ MessageTransferBody publish = new MessageTransferBody(
+ (byte)0,
+ (byte)9,
+ MessageTransferBody.getClazz((byte)0,(byte)9),
+ MessageTransferBody.getMethod((byte)0,(byte)9),
+ null, // AMQShortString appId
+ null, // FieldTable applicationHeaders
+ null, // Content body
+ null, // AMQShortString contentEncoding
+ null, // AMQShortString contentType
+ null, // AMQShortString correlationId
+ (short)0, // short deliveryMode
+ null, // AMQShortString destination
+ null, // AMQShortString exchange
+ 0L, // long expiration
+ immediate, // boolean immediate
+ false, // boolean mandatory
+ null, // AMQShortString messageId
+ (short)0, // short priority
+ false, // boolean redelivered
+ null, // AMQShortString replyTo
+ null, // AMQShortString routingKey
+ null, // byte[] securityToken
+ 0, // int ticket
+ 0L, // long timestamp
+ null, // AMQShortString transactionId
+ 0L, // long ttl
+ null); // AMQShortString userId
+
+ return new AMQMessage(_messageStore, publish, _txnContext);
+ }
+
+}
diff --git a/java/systests/src/test/java/org/apache/qpid/server/queue/MockProtocolSession.java b/java/systests/src/main/java/org/apache/qpid/server/queue/MockProtocolSession.java
index 400b21c5b1..ca357976b2 100644
--- a/java/systests/src/test/java/org/apache/qpid/server/queue/MockProtocolSession.java
+++ b/java/systests/src/main/java/org/apache/qpid/server/queue/MockProtocolSession.java
@@ -24,10 +24,12 @@ import org.apache.qpid.AMQException;
import org.apache.qpid.framing.AMQDataBlock;
import org.apache.qpid.framing.AMQMethodBody;
import org.apache.qpid.framing.FieldTable;
+import org.apache.qpid.framing.AMQShortString;
+import org.apache.qpid.framing.VersionSpecificRegistry;
import org.apache.qpid.protocol.AMQMethodEvent;
import org.apache.qpid.protocol.AMQMethodListener;
import org.apache.qpid.server.AMQChannel;
-import org.apache.qpid.server.exchange.ExchangeRegistry;
+import org.apache.qpid.server.virtualhost.VirtualHost;
import org.apache.qpid.server.protocol.AMQProtocolSession;
import org.apache.qpid.server.state.AMQStateManager;
import org.apache.qpid.server.store.MessageStore;
@@ -35,7 +37,6 @@ import org.apache.qpid.server.store.MessageStore;
import javax.security.sasl.SaslServer;
import java.util.HashMap;
import java.util.Map;
-import java.util.concurrent.atomic.AtomicInteger;
/**
* A protocol session that can be used for testing purposes.
@@ -46,13 +47,8 @@ public class MockProtocolSession implements AMQProtocolSession
private Map<Integer, AMQChannel> _channelMap = new HashMap<Integer, AMQChannel>();
- // Keeps a tally of connections for logging and debugging
- private static AtomicInteger _ConnectionId;
- static { _ConnectionId = new AtomicInteger(0); }
-
public MockProtocolSession(MessageStore messageStore)
{
- _ConnectionId.incrementAndGet();
_messageStore = messageStore;
}
@@ -64,12 +60,12 @@ public class MockProtocolSession implements AMQProtocolSession
{
}
- public String getContextKey()
+ public AMQShortString getContextKey()
{
return null;
}
- public void setContextKey(String contextKey)
+ public void setContextKey(AMQShortString contextKey)
{
}
@@ -142,110 +138,116 @@ public class MockProtocolSession implements AMQProtocolSession
public void setClientProperties(FieldTable clientProperties)
{
}
-
public Object getClientIdentifier()
{
return null;
}
- public void closeChannelRequest(int channelId, int replyCode, String replyText) throws AMQException {
- // TODO Auto-generated method stub
-
- }
-
- public void closeChannelResponse(int channelId, long requestId) throws AMQException {
- // TODO Auto-generated method stub
-
- }
-
- public void closeSessionRequest(int replyCode, String replyText, int classId, int methodId) throws AMQException {
- // TODO Auto-generated method stub
-
- }
-
- public void closeSessionRequest(int replyCode, String replyText) throws AMQException {
- // TODO Auto-generated method stub
-
- }
-
- public void closeSessionResponse(long requestId) throws AMQException {
- // TODO Auto-generated method stub
-
- }
-
- public void setFrameMax(long size) {
- // TODO Auto-generated method stub
-
- }
-
- public long getFrameMax() {
- // TODO Auto-generated method stub
- return 0;
- }
-
- public QueueRegistry getQueueRegistry() {
- // TODO Auto-generated method stub
- return null;
- }
-
- public ExchangeRegistry getExchangeRegistry() {
- // TODO Auto-generated method stub
- return null;
- }
+ public VirtualHost getVirtualHost()
+ {
+ return null; //To change body of implemented methods use File | Settings | File Templates.
+ }
- public AMQStateManager getStateManager() {
- // TODO Auto-generated method stub
- return null;
- }
+ public void setVirtualHost(VirtualHost virtualHost)
+ {
+ //To change body of implemented methods use File | Settings | File Templates.
+ }
- public byte getMajor() {
- // TODO Auto-generated method stub
- return 0;
- }
+ public void addSessionCloseTask(Task task)
+ {
+ //To change body of implemented methods use File | Settings | File Templates.
+ }
- public byte getMinor() {
- // TODO Auto-generated method stub
- return 0;
- }
+ public void removeSessionCloseTask(Task task)
+ {
+ //To change body of implemented methods use File | Settings | File Templates.
+ }
- public boolean versionEquals(byte major, byte minor) {
- // TODO Auto-generated method stub
- return false;
- }
+ public byte getProtocolMajorVersion()
+ {
+ return 0; //To change body of implemented methods use File | Settings | File Templates.
+ }
- public void checkMethodBodyVersion(AMQMethodBody methodBody) {
- // TODO Auto-generated method stub
-
- }
+ public byte getProtocolMinorVersion()
+ {
+ return 9; //To change body of implemented methods use File | Settings | File Templates.
+ }
+
+ public boolean isProtocolVersionEqual(byte major, byte minor)
+ {
+ return major == 0 && minor == 9;
+ }
+
+ public void checkMethodBodyVersion(AMQMethodBody methodBody)
+ {
- public long writeRequest(int channelNum, AMQMethodBody methodBody, AMQMethodListener methodListener) {
- // TODO Auto-generated method stub
- return 0;
- }
+ }
- public void writeResponse(int channelNum, long requestId, AMQMethodBody methodBody) {
- // TODO Auto-generated method stub
-
- }
+ public VersionSpecificRegistry getRegistry()
+ {
+ return null; //To change body of implemented methods use File | Settings | File Templates.
+ }
+
+ public long getConnectionId()
+ {
+ return 0L;
+ }
+
+ public AMQStateManager getStateManager()
+ {
+ return null;
+ }
+
+ public long getFrameMax()
+ {
+ return 0L;
+ }
+
+ public void setFrameMax(long size)
+ {
+
+ }
+
+ public void closeChannelRequest(int channelId, int replyCode, AMQShortString replyText) throws AMQException
+ {
+
+ }
+
+ public void closeChannelResponse(int channelId, long requestId) throws AMQException
+ {
+
+ }
+
+ public void closeSessionRequest(int replyCode, AMQShortString replyText, int classId, int methodId) throws AMQException
+ {
+
+ }
- public void writeResponse(AMQMethodEvent evt, AMQMethodBody response) {
- // TODO Auto-generated method stub
-
- }
+ public void closeSessionRequest(int replyCode, AMQShortString replyText) throws AMQException
+ {
+
+ }
- public int getConnectionId()
+ public void closeSessionResponse(long requestId) throws AMQException
{
- return _ConnectionId.get();
+
+ }
+
+ public long writeRequest(int channelNum, AMQMethodBody methodBody,
+ AMQMethodListener methodListener)
+ {
+ return 0L;
}
- public void addSessionCloseTask(Task task)
+ public void writeResponse(int channelNum, long requestId, AMQMethodBody methodBody)
{
- //To change body of implemented methods use File | Settings | File Templates.
+
}
- public void removeSessionCloseTask(Task task)
+ public void writeResponse(AMQMethodEvent evt, AMQMethodBody response)
{
- //To change body of implemented methods use File | Settings | File Templates.
+
}
+
}
diff --git a/java/systests/src/test/java/org/apache/qpid/server/queue/SubscriptionManagerTest.java b/java/systests/src/main/java/org/apache/qpid/server/queue/SubscriptionManagerTest.java
index d3ec3c11d4..d3ec3c11d4 100644
--- a/java/systests/src/test/java/org/apache/qpid/server/queue/SubscriptionManagerTest.java
+++ b/java/systests/src/main/java/org/apache/qpid/server/queue/SubscriptionManagerTest.java
diff --git a/java/systests/src/test/java/org/apache/qpid/server/queue/SubscriptionSetTest.java b/java/systests/src/main/java/org/apache/qpid/server/queue/SubscriptionSetTest.java
index bcf54693d3..bcf54693d3 100644
--- a/java/systests/src/test/java/org/apache/qpid/server/queue/SubscriptionSetTest.java
+++ b/java/systests/src/main/java/org/apache/qpid/server/queue/SubscriptionSetTest.java
diff --git a/java/systests/src/test/java/org/apache/qpid/server/queue/SubscriptionTestHelper.java b/java/systests/src/main/java/org/apache/qpid/server/queue/SubscriptionTestHelper.java
index fea3c93280..b3574ecba4 100644
--- a/java/systests/src/test/java/org/apache/qpid/server/queue/SubscriptionTestHelper.java
+++ b/java/systests/src/main/java/org/apache/qpid/server/queue/SubscriptionTestHelper.java
@@ -67,6 +67,12 @@ public class SubscriptionTestHelper implements Subscription
return isSuspended;
}
+ public boolean wouldSuspend(AMQMessage msg)
+ {
+ return isSuspended;
+ }
+
+
public void queueDeleted(AMQQueue queue)
{
}
diff --git a/java/systests/src/test/java/org/apache/qpid/server/store/SkeletonMessageStore.java b/java/systests/src/main/java/org/apache/qpid/server/store/SkeletonMessageStore.java
index bc0a8a7d64..4468bfe13b 100644
--- a/java/systests/src/test/java/org/apache/qpid/server/store/SkeletonMessageStore.java
+++ b/java/systests/src/main/java/org/apache/qpid/server/store/SkeletonMessageStore.java
@@ -7,9 +7,9 @@
* 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
@@ -20,11 +20,12 @@
*/
package org.apache.qpid.server.store;
-import org.apache.qpid.server.queue.AMQMessage;
-import org.apache.qpid.server.queue.AMQQueue;
-import org.apache.qpid.server.queue.QueueRegistry;
-import org.apache.qpid.AMQException;
import org.apache.commons.configuration.Configuration;
+import org.apache.qpid.AMQException;
+import org.apache.qpid.framing.AMQShortString;
+import org.apache.qpid.server.queue.AMQQueue;
+import org.apache.qpid.server.queue.MessageMetaData;
+import org.apache.qpid.server.virtualhost.VirtualHost;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
@@ -40,63 +41,94 @@ public class SkeletonMessageStore implements MessageStore
public void configure(String base, Configuration config) throws Exception
{
}
-
- public void configure(QueueRegistry queueRegistry, String base, Configuration config) throws Exception
+
+ public void configure(VirtualHost virtualHost, String base, Configuration config) throws Exception
{
+ //To change body of implemented methods use File | Settings | File Templates.
}
public void close() throws Exception
{
}
- public void put(AMQMessage msg)
+ public void removeMessage(StoreContext s, Long messageId)
{
}
- public void removeMessage(long messageId)
+ public void createQueue(AMQQueue queue) throws AMQException
+ {
+ }
+
+ public void beginTran(StoreContext s) throws AMQException
{
}
- public void createQueue(AMQQueue queue) throws AMQException
+ public boolean inTran(StoreContext sc)
{
+ return false;
}
- public void removeQueue(String name) throws AMQException
+ public void commitTran(StoreContext storeContext) throws AMQException
{
}
- public void enqueueMessage(String name, long messageId) throws AMQException
+ public void abortTran(StoreContext storeContext) throws AMQException
{
}
- public void dequeueMessage(String name, long messageId) throws AMQException
+ public List<AMQQueue> createQueues() throws AMQException
{
+ return null;
}
- public void beginTran() throws AMQException
+ public Long getNewMessageId()
{
+ return _messageId.getAndIncrement();
}
- public boolean inTran()
+ public void storeContentChunk(StoreContext sc, Long messageId, int index, byte[] content, boolean lastContentBody) throws AMQException
{
- return false;
+
}
-
- public void commitTran() throws AMQException
+
+ public void storeMessageMetaData(StoreContext sc, Long messageId, MessageMetaData messageMetaData) throws AMQException
{
+
}
- public void abortTran() throws AMQException
+ public MessageMetaData getMessageMetaData(Long messageId) throws AMQException
{
+ return null;
}
- public List<AMQQueue> createQueues() throws AMQException
+ public byte[] getContentChunk(Long messageId, int index) throws AMQException
{
return null;
}
- public long getNewMessageId()
+ public void removeQueue(AMQShortString name) throws AMQException
{
- return _messageId.getAndIncrement();
+
+ }
+
+ public void enqueueMessage(StoreContext context, AMQShortString name, Long messageId) throws AMQException
+ {
+
+ }
+
+ public void dequeueMessage(StoreContext context, AMQShortString name, Long messageId) throws AMQException
+ {
+
+ }
+
+ public void storeContentBodyChunk(StoreContext context, Long messageId, int index, byte[] contentBody, boolean lastContentBody) throws AMQException
+ {
+
}
+
+ public byte[] getContentBodyChunk(Long messageId, int index) throws AMQException
+ {
+ return new byte[0];
+ }
+
}
diff --git a/java/systests/src/main/java/org/apache/qpid/server/store/TestReferenceCounting.java b/java/systests/src/main/java/org/apache/qpid/server/store/TestReferenceCounting.java
new file mode 100644
index 0000000000..5d60596c64
--- /dev/null
+++ b/java/systests/src/main/java/org/apache/qpid/server/store/TestReferenceCounting.java
@@ -0,0 +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.server.store;
+
+import junit.framework.TestCase;
+import org.apache.qpid.AMQException;
+import org.apache.qpid.framing.MessageTransferBody;
+import org.apache.qpid.server.queue.AMQMessage;
+import org.apache.qpid.server.queue.MessageHandleFactory;
+import org.apache.qpid.server.txn.TransactionalContext;
+
+/**
+ * Tests that reference counting works correctly with AMQMessage and the message store
+ */
+public class TestReferenceCounting extends TestCase
+{
+ private TransactionalContext txnContext = null;
+
+ private TestableMemoryMessageStore _store;
+
+ private StoreContext _storeContext = new StoreContext();
+
+ protected void setUp() throws Exception
+ {
+ super.setUp();
+ _store = new TestableMemoryMessageStore();
+ }
+
+ /**
+ * Check that when the reference count is decremented the message removes itself from the store
+ */
+ public void testMessageGetsRemoved() throws AMQException
+ {
+ // TODO: fix hardcoded protocol version data
+ AMQMessage message = new AMQMessage(_store,
+ new MessageTransferBody((byte)0,
+ (byte)9,
+ MessageTransferBody.getClazz((byte)0,(byte)9),
+ MessageTransferBody.getMethod((byte)0,(byte)9),
+ null, // AMQShortString appId
+ null, // FieldTable applicationHeaders
+ null, // Content body
+ null, // AMQShortString contentEncoding
+ null, // AMQShortString contentType
+ null, // AMQShortString correlationId
+ (short)0, // short deliveryMode
+ null, // AMQShortString destination
+ null, // AMQShortString exchange
+ 0L, // long expiration
+ false, // boolean immediate
+ false, // boolean mandatory
+ null, // AMQShortString messageId
+ (short)0, // short priority
+ false, // boolean redelivered
+ null, // AMQShortString replyTo
+ null, // AMQShortString routingKey
+ null, // byte[] securityToken
+ 0, // int ticket
+ 0L, // long timestamp
+ null, // AMQShortString transactionId
+ 0L, // long ttl
+ null), // AMQShortString userId
+ txnContext);
+ message.incrementReference();
+ // we call routing complete to set up the handle
+// message.routingComplete(_store, _storeContext, new MessageHandleFactory());
+ assertTrue(_store.getMessageMetaDataMap().size() == 1);
+ message.decrementReference(_storeContext);
+ assertTrue(_store.getMessageMetaDataMap().size() == 0);
+ }
+
+ public void testMessageRemains() throws AMQException
+ {
+ // TODO: fix hardcoded protocol version data
+ AMQMessage message = new AMQMessage(_store,
+ new MessageTransferBody((byte)0,
+ (byte)9,
+ MessageTransferBody.getClazz((byte)0,(byte)9),
+ MessageTransferBody.getMethod((byte)0,(byte)9),
+ null, // AMQShortString appId
+ null, // FieldTable applicationHeaders
+ null, // Content body
+ null, // AMQShortString contentEncoding
+ null, // AMQShortString contentType
+ null, // AMQShortString correlationId
+ (short)0, // short deliveryMode
+ null, // AMQShortString destination
+ null, // AMQShortString exchange
+ 0L, // long expiration
+ false, // boolean immediate
+ false, // boolean mandatory
+ null, // AMQShortString messageId
+ (short)0, // short priority
+ false, // boolean redelivered
+ null, // AMQShortString replyTo
+ null, // AMQShortString routingKey
+ null, // byte[] securityToken
+ 0, // int ticket
+ 0L, // long timestamp
+ null, // AMQShortString transactionId
+ 0L, // long ttl
+ null), // AMQShortString userId
+ txnContext);
+ message.incrementReference();
+ // we call routing complete to set up the handle
+// message.routingComplete(_store, _storeContext, new MessageHandleFactory());
+ assertTrue(_store.getMessageMetaDataMap().size() == 1);
+ message.incrementReference();
+ message.decrementReference(_storeContext);
+ assertTrue(_store.getMessageMetaDataMap().size() == 1);
+ }
+
+ public static junit.framework.Test suite()
+ {
+ return new junit.framework.TestSuite(TestReferenceCounting.class);
+ }
+}
diff --git a/java/systests/src/test/java/org/apache/qpid/server/store/TestableMemoryMessageStore.java b/java/systests/src/main/java/org/apache/qpid/server/store/TestableMemoryMessageStore.java
index be7687a22c..fc775c904c 100644
--- a/java/systests/src/test/java/org/apache/qpid/server/store/TestableMemoryMessageStore.java
+++ b/java/systests/src/main/java/org/apache/qpid/server/store/TestableMemoryMessageStore.java
@@ -7,9 +7,9 @@
* 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
@@ -20,10 +20,11 @@
*/
package org.apache.qpid.server.store;
-import org.apache.qpid.server.queue.AMQMessage;
+import org.apache.qpid.server.queue.MessageMetaData;
-import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.List;
/**
* Adds some extra methods to the memory message store for testing purposes.
@@ -32,11 +33,17 @@ public class TestableMemoryMessageStore extends MemoryMessageStore
{
public TestableMemoryMessageStore()
{
- _messageMap = new ConcurrentHashMap<Long, AMQMessage>();
+ _metaDataMap = new ConcurrentHashMap<Long, MessageMetaData>();
+ _contentBodyMap = new ConcurrentHashMap<Long, List<byte[]>>();
+ }
+
+ public ConcurrentMap<Long, MessageMetaData> getMessageMetaDataMap()
+ {
+ return _metaDataMap;
}
- public ConcurrentMap<Long, AMQMessage> getMessageMap()
+ public ConcurrentMap<Long, List<byte[]>> getContentBodyMap()
{
- return _messageMap;
+ return _contentBodyMap;
}
}
diff --git a/java/systests/src/test/java/org/apache/qpid/server/txn/TxnBufferTest.java b/java/systests/src/main/java/org/apache/qpid/server/txn/TxnBufferTest.java
index ac5c60a931..1d9e30c24e 100644
--- a/java/systests/src/test/java/org/apache/qpid/server/txn/TxnBufferTest.java
+++ b/java/systests/src/main/java/org/apache/qpid/server/txn/TxnBufferTest.java
@@ -7,9 +7,9 @@
* 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
@@ -20,23 +20,23 @@
*/
package org.apache.qpid.server.txn;
+import junit.framework.TestCase;
import org.apache.qpid.AMQException;
import org.apache.qpid.server.store.MessageStore;
import org.apache.qpid.server.store.TestableMemoryMessageStore;
+import org.apache.qpid.server.store.StoreContext;
import java.util.LinkedList;
-import junit.framework.TestCase;
-
public class TxnBufferTest extends TestCase
{
- private final LinkedList<MockOp> ops = new LinkedList<MockOp>();
+ private final LinkedList<MockOp> ops = new LinkedList<MockOp>();
public void testCommit() throws AMQException
{
MockStore store = new MockStore();
- TxnBuffer buffer = new TxnBuffer(store);
+ TxnBuffer buffer = new TxnBuffer();
buffer.enlist(new MockOp().expectPrepare().expectCommit());
//check relative ordering
MockOp op = new MockOp().expectPrepare().expectPrepare().expectCommit().expectCommit();
@@ -44,7 +44,7 @@ public class TxnBufferTest extends TestCase
buffer.enlist(op);
buffer.enlist(new MockOp().expectPrepare().expectCommit());
- buffer.commit();
+ buffer.commit(null);
validateOps();
store.validate();
@@ -54,12 +54,12 @@ public class TxnBufferTest extends TestCase
{
MockStore store = new MockStore();
- TxnBuffer buffer = new TxnBuffer(store);
+ TxnBuffer buffer = new TxnBuffer();
buffer.enlist(new MockOp().expectRollback());
buffer.enlist(new MockOp().expectRollback());
buffer.enlist(new MockOp().expectRollback());
- buffer.rollback();
+ buffer.rollback(null);
validateOps();
store.validate();
@@ -68,17 +68,17 @@ public class TxnBufferTest extends TestCase
public void testCommitWithFailureDuringPrepare() throws AMQException
{
MockStore store = new MockStore();
- store.expectBegin().expectAbort();
+ store.beginTran(null);
- TxnBuffer buffer = new TxnBuffer(store);
- buffer.containsPersistentChanges();
+ TxnBuffer buffer = new TxnBuffer();
+ buffer.enlist(new StoreMessageOperation(store));
buffer.enlist(new MockOp().expectPrepare().expectUndoPrepare());
buffer.enlist(new TxnTester(store));
buffer.enlist(new MockOp().expectPrepare().expectUndoPrepare());
buffer.enlist(new FailedPrepare());
buffer.enlist(new MockOp());
- buffer.commit();
+ buffer.commit(null);
validateOps();
store.validate();
}
@@ -86,16 +86,17 @@ public class TxnBufferTest extends TestCase
public void testCommitWithPersistance() throws AMQException
{
MockStore store = new MockStore();
- store.expectBegin().expectCommit();
+ store.beginTran(null);
+ store.expectCommit();
- TxnBuffer buffer = new TxnBuffer(store);
+ TxnBuffer buffer = new TxnBuffer();
buffer.enlist(new MockOp().expectPrepare().expectCommit());
buffer.enlist(new MockOp().expectPrepare().expectCommit());
buffer.enlist(new MockOp().expectPrepare().expectCommit());
+ buffer.enlist(new StoreMessageOperation(store));
buffer.enlist(new TxnTester(store));
- buffer.containsPersistentChanges();
- buffer.commit();
+ buffer.commit(null);
validateOps();
store.validate();
}
@@ -114,7 +115,7 @@ public class TxnBufferTest extends TestCase
}
class MockOp implements TxnOp
- {
+ {
final Object PREPARE = "PREPARE";
final Object COMMIT = "COMMIT";
final Object UNDO_PREPARE = "UNDO_PREPARE";
@@ -127,12 +128,12 @@ public class TxnBufferTest extends TestCase
ops.add(this);
}
- public void prepare()
+ public void prepare(StoreContext context)
{
assertEquals(expected.removeLast(), PREPARE);
}
- public void commit()
+ public void commit(StoreContext context)
{
assertEquals(expected.removeLast(), COMMIT);
}
@@ -142,7 +143,7 @@ public class TxnBufferTest extends TestCase
assertEquals(expected.removeLast(), UNDO_PREPARE);
}
- public void rollback()
+ public void rollback(StoreContext context)
{
assertEquals(expected.removeLast(), ROLLBACK);
}
@@ -193,25 +194,24 @@ public class TxnBufferTest extends TestCase
private final LinkedList expected = new LinkedList();
private boolean inTran;
- public void beginTran() throws AMQException
+ public void beginTran(StoreContext context) throws AMQException
{
- assertEquals(expected.removeLast(), BEGIN);
inTran = true;
}
-
- public void commitTran() throws AMQException
+
+ public void commitTran(StoreContext context) throws AMQException
{
assertEquals(expected.removeLast(), COMMIT);
inTran = false;
}
-
- public void abortTran() throws AMQException
+
+ public void abortTran(StoreContext context) throws AMQException
{
assertEquals(expected.removeLast(), ABORT);
inTran = false;
}
- public boolean inTran()
+ public boolean inTran(StoreContext context)
{
return inTran;
}
@@ -249,23 +249,23 @@ public class TxnBufferTest extends TestCase
}
class NullOp implements TxnOp
- {
- public void prepare() throws AMQException
+ {
+ public void prepare(StoreContext context) throws AMQException
{
}
- public void commit()
+ public void commit(StoreContext context)
{
}
public void undoPrepare()
{
}
- public void rollback()
+ public void rollback(StoreContext context)
{
}
}
class FailedPrepare extends NullOp
- {
+ {
public void prepare() throws AMQException
{
throw new AMQException("Fail!");
@@ -273,9 +273,11 @@ public class TxnBufferTest extends TestCase
}
class TxnTester extends NullOp
- {
+ {
private final MessageStore store;
+ private final StoreContext context = new StoreContext();
+
TxnTester(MessageStore store)
{
this.store = store;
@@ -283,12 +285,12 @@ public class TxnBufferTest extends TestCase
public void prepare() throws AMQException
{
- assertTrue("Expected prepare to be performed under txn", store.inTran());
+ assertTrue("Expected prepare to be performed under txn", store.inTran(context));
}
public void commit()
{
- assertTrue("Expected commit not to be performed under txn", !store.inTran());
+ assertTrue("Expected commit not to be performed under txn", !store.inTran(context));
}
}
diff --git a/java/systests/src/test/java/org/apache/qpid/server/util/AveragedRun.java b/java/systests/src/main/java/org/apache/qpid/server/util/AveragedRun.java
index 1d17985ab5..1d17985ab5 100644
--- a/java/systests/src/test/java/org/apache/qpid/server/util/AveragedRun.java
+++ b/java/systests/src/main/java/org/apache/qpid/server/util/AveragedRun.java
diff --git a/java/systests/src/test/java/org/apache/qpid/server/util/RunStats.java b/java/systests/src/main/java/org/apache/qpid/server/util/RunStats.java
index ec67fc68b3..ec67fc68b3 100644
--- a/java/systests/src/test/java/org/apache/qpid/server/util/RunStats.java
+++ b/java/systests/src/main/java/org/apache/qpid/server/util/RunStats.java
diff --git a/java/systests/src/test/java/org/apache/qpid/server/util/TestApplicationRegistry.java b/java/systests/src/main/java/org/apache/qpid/server/util/TestApplicationRegistry.java
index f801daf27c..849285e6d6 100644
--- a/java/systests/src/test/java/org/apache/qpid/server/util/TestApplicationRegistry.java
+++ b/java/systests/src/main/java/org/apache/qpid/server/util/TestApplicationRegistry.java
@@ -29,14 +29,18 @@ import org.apache.qpid.server.management.NoopManagedObjectRegistry;
import org.apache.qpid.server.queue.DefaultQueueRegistry;
import org.apache.qpid.server.queue.QueueRegistry;
import org.apache.qpid.server.registry.ApplicationRegistry;
+import org.apache.qpid.server.registry.IApplicationRegistry;
import org.apache.qpid.server.security.auth.AuthenticationManager;
import org.apache.qpid.server.security.auth.NullAuthenticationManager;
import org.apache.qpid.server.store.MessageStore;
import org.apache.qpid.server.store.TestableMemoryMessageStore;
+import org.apache.qpid.server.virtualhost.VirtualHost;
+import org.apache.qpid.server.virtualhost.VirtualHostRegistry;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.MapConfiguration;
import java.util.HashMap;
+import java.util.Collection;
public class TestApplicationRegistry extends ApplicationRegistry
{
@@ -51,6 +55,7 @@ public class TestApplicationRegistry extends ApplicationRegistry
private AuthenticationManager _authenticationManager;
private MessageStore _messageStore;
+ private VirtualHost _vHost;
public TestApplicationRegistry()
{
@@ -59,10 +64,12 @@ public class TestApplicationRegistry extends ApplicationRegistry
public void initialise() throws Exception
{
- _managedObjectRegistry = new NoopManagedObjectRegistry();
- _queueRegistry = new DefaultQueueRegistry();
- _exchangeFactory = new DefaultExchangeFactory();
- _exchangeRegistry = new DefaultExchangeRegistry(_exchangeFactory);
+ IApplicationRegistry appRegistry = ApplicationRegistry.getInstance();
+ _managedObjectRegistry = appRegistry.getManagedObjectRegistry();
+ _vHost = appRegistry.getVirtualHostRegistry().getVirtualHost("test");
+ _queueRegistry = _vHost.getQueueRegistry();
+ _exchangeFactory = _vHost.getExchangeFactory();
+ _exchangeRegistry = _vHost.getExchangeRegistry();
_authenticationManager = new NullAuthenticationManager();
_messageStore = new TestableMemoryMessageStore();
@@ -99,6 +106,16 @@ public class TestApplicationRegistry extends ApplicationRegistry
return _authenticationManager;
}
+ public Collection<String> getVirtualHostNames()
+ {
+ return null; //To change body of implemented methods use File | Settings | File Templates.
+ }
+
+ public VirtualHostRegistry getVirtualHostRegistry()
+ {
+ return null; //To change body of implemented methods use File | Settings | File Templates.
+ }
+
public MessageStore getMessageStore()
{
return _messageStore;
diff --git a/java/systests/src/test/java/org/apache/qpid/server/util/TimedRun.java b/java/systests/src/main/java/org/apache/qpid/server/util/TimedRun.java
index 1291380311..1291380311 100644
--- a/java/systests/src/test/java/org/apache/qpid/server/util/TimedRun.java
+++ b/java/systests/src/main/java/org/apache/qpid/server/util/TimedRun.java
diff --git a/java/systests/src/test/java/org/apache/qpid/test/VMBrokerSetup.java b/java/systests/src/main/java/org/apache/qpid/test/VMBrokerSetup.java
index e859fac4af..e859fac4af 100644
--- a/java/systests/src/test/java/org/apache/qpid/test/VMBrokerSetup.java
+++ b/java/systests/src/main/java/org/apache/qpid/test/VMBrokerSetup.java
diff --git a/java/client/src/main/java/log4j.properties b/java/systests/src/main/java/systests.log4j
index 6d596d1d19..6d596d1d19 100644
--- a/java/client/src/main/java/log4j.properties
+++ b/java/systests/src/main/java/systests.log4j
diff --git a/java/systests/src/old_test/java/org/apache/qpid/server/queue/SendPerfTest.java b/java/systests/src/old_test/java/org/apache/qpid/server/queue/SendPerfTest.java
index 6490b9f270..2c5712fd35 100644
--- a/java/systests/src/old_test/java/org/apache/qpid/server/queue/SendPerfTest.java
+++ b/java/systests/src/old_test/java/org/apache/qpid/server/queue/SendPerfTest.java
@@ -7,9 +7,9 @@
* 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
@@ -27,6 +27,9 @@ import org.apache.qpid.framing.ContentBody;
import org.apache.qpid.framing.ContentHeaderBody;
import org.apache.qpid.framing.FieldTable;
import org.apache.qpid.server.AMQChannel;
+import org.apache.qpid.server.RequiredDeliveryException;
+import org.apache.qpid.server.txn.TransactionalContext;
+import org.apache.qpid.server.txn.NonTransactionalContext;
import org.apache.qpid.server.exchange.AbstractExchange;
import org.apache.qpid.server.exchange.Exchange;
import org.apache.qpid.server.handler.OnCurrentThreadExecutor;
@@ -43,6 +46,7 @@ import org.apache.qpid.server.util.TimedRun;
import java.util.ArrayList;
import java.util.List;
+import java.util.LinkedList;
public class SendPerfTest extends TimedRun
{
@@ -101,13 +105,16 @@ public class SendPerfTest extends TimedRun
ContentHeaderBody header = new ContentHeaderBody();
List<ContentBody> body = new ArrayList<ContentBody>();
MessageStore messageStore = new SkeletonMessageStore();
+ // channel can be null since it is only used in ack processing which does not apply to this test
+ TransactionalContext txContext = new NonTransactionalContext(messageStore, null,
+ new LinkedList<RequiredDeliveryException>());
body.add(new ContentBody());
+ MessageHandleFactory factory = new MessageHandleFactory();
for (int i = 0; i < count; i++)
{
- for (AMQQueue q : queues)
- {
- q.deliver(new AMQMessage(messageStore, i, publish, header, body));
- }
+ // this routes and delivers the message
+ AMQMessage msg = new AMQMessage(i, publish, txContext, header, queues, body, messageStore,
+ factory);
}
}
diff --git a/java/systests/src/old_test/java/org/apache/qpid/test/unit/ack/DisconnectAndRedeliverTest.java b/java/systests/src/old_test/java/org/apache/qpid/test/unit/ack/DisconnectAndRedeliverTest.java
index a3e555aac9..3e35e3c85b 100644
--- a/java/systests/src/old_test/java/org/apache/qpid/test/unit/ack/DisconnectAndRedeliverTest.java
+++ b/java/systests/src/old_test/java/org/apache/qpid/test/unit/ack/DisconnectAndRedeliverTest.java
@@ -7,9 +7,9 @@
* 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
@@ -20,22 +20,19 @@
*/
package org.apache.qpid.test.unit.ack;
+import junit.framework.TestCase;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;
import org.apache.qpid.client.AMQConnection;
import org.apache.qpid.client.AMQQueue;
import org.apache.qpid.client.AMQSession;
-import org.apache.qpid.client.vmbroker.AMQVMBrokerCreationException;
import org.apache.qpid.client.transport.TransportConnection;
import org.apache.qpid.server.registry.ApplicationRegistry;
import org.apache.qpid.server.store.TestableMemoryMessageStore;
import org.apache.qpid.server.util.TestApplicationRegistry;
-import org.apache.qpid.test.VMBrokerSetup;
import javax.jms.*;
-import junit.framework.TestCase;
-
public class DisconnectAndRedeliverTest extends TestCase
{
private static final Logger _logger = Logger.getLogger(DisconnectAndRedeliverTest.class);
@@ -55,12 +52,14 @@ public class DisconnectAndRedeliverTest extends TestCase
protected void setUp() throws Exception
{
super.setUp();
+ TransportConnection.createVMBroker(1);
ApplicationRegistry.initialise(new TestApplicationRegistry(), 1);
}
protected void tearDown() throws Exception
{
super.tearDown();
+ TransportConnection.killAllVMBrokers();
}
/**
@@ -82,7 +81,7 @@ public class DisconnectAndRedeliverTest extends TestCase
((AMQSession) consumerSession).declareExchangeSynch("amq.direct", "direct");
Connection con2 = new AMQConnection("vm://:1", "guest", "guest", "producer1", "/test");
-
+
Session producerSession = con2.createSession(false, Session.CLIENT_ACKNOWLEDGE);
MessageProducer producer = producerSession.createProducer(queue);
@@ -149,7 +148,7 @@ public class DisconnectAndRedeliverTest extends TestCase
_logger.info("No messages redelivered as is expected");
con.close();
- _logger.info("Actually:" + store.getMessageMap().size());
+ _logger.info("Actually:" + store.getMessageMetaDataMap().size());
// assertTrue(store.getMessageMap().size() == 0);
}
@@ -204,13 +203,13 @@ public class DisconnectAndRedeliverTest extends TestCase
assertNull(tm);
_logger.info("No messages redelivered as is expected");
- _logger.info("Actually:" + store.getMessageMap().size());
- assertTrue(store.getMessageMap().size() == 0);
+ _logger.info("Actually:" + store.getMessageMetaDataMap().size());
+ assertTrue(store.getMessageMetaDataMap().size() == 0);
con.close();
}
public static junit.framework.Test suite()
{
- return new VMBrokerSetup(new junit.framework.TestSuite(DisconnectAndRedeliverTest.class));
+ return new junit.framework.TestSuite(DisconnectAndRedeliverTest.class);
}
}
diff --git a/java/systests/src/test/java/org/apache/qpid/server/exchange/AbstractHeadersExchangeTestBase.java b/java/systests/src/test/java/org/apache/qpid/server/exchange/AbstractHeadersExchangeTestBase.java
deleted file mode 100644
index 6320a2c1be..0000000000
--- a/java/systests/src/test/java/org/apache/qpid/server/exchange/AbstractHeadersExchangeTestBase.java
+++ /dev/null
@@ -1,247 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.exchange;
-
-import junit.framework.TestCase;
-
-import org.apache.mina.common.ByteBuffer;
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.message.MessageHeaders;
-import org.apache.qpid.framing.*;
-import org.apache.qpid.server.queue.AMQMessage;
-import org.apache.qpid.server.queue.AMQQueue;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.server.store.MessageStore;
-import org.apache.qpid.server.store.SkeletonMessageStore;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-public class AbstractHeadersExchangeTestBase extends TestCase
-{
- private final HeadersExchange exchange = new HeadersExchange();
- protected final Set<TestQueue> queues = new HashSet<TestQueue>();
- private int count;
-
- public void testDoNothing()
- {
- // this is here only to make junit under Eclipse happy
- }
-
- protected TestQueue bindDefault(String... bindings) throws AMQException
- {
- return bind("Queue" + (++count), bindings);
- }
-
- protected TestQueue bind(String queueName, String... bindings) throws AMQException
- {
- return bind(queueName, getHeaders(bindings));
- }
-
- protected TestQueue bind(String queue, FieldTable bindings) throws AMQException
- {
- return bind(new TestQueue(queue), bindings);
- }
-
- protected TestQueue bind(TestQueue queue, String... bindings) throws AMQException
- {
- return bind(queue, getHeaders(bindings));
- }
-
- protected TestQueue bind(TestQueue queue, FieldTable bindings) throws AMQException
- {
- queues.add(queue);
- exchange.registerQueue(null, queue, bindings);
- return queue;
- }
-
-
- protected void route(Message m) throws AMQException
- {
- m.route(exchange);
- }
-
- protected void routeAndTest(Message m, TestQueue... expected) throws AMQException
- {
- routeAndTest(m, false, Arrays.asList(expected));
- }
-
- protected void routeAndTest(Message m, boolean expectReturn, TestQueue... expected) throws AMQException
- {
- routeAndTest(m, expectReturn, Arrays.asList(expected));
- }
-
- protected void routeAndTest(Message m, List<TestQueue> expected) throws AMQException
- {
- routeAndTest(m, false, expected);
- }
-
- protected void routeAndTest(Message m, boolean expectReturn, List<TestQueue> expected) throws AMQException
- {
- try
- {
- route(m);
- assertFalse("Expected "+m+" to be returned due to manadatory flag, and lack of routing",expectReturn);
- for (TestQueue q : queues)
- {
- if (expected.contains(q))
- {
- assertTrue("Expected " + m + " to be delivered to " + q, m.isInQueue(q));
- //assert m.isInQueue(q) : "Expected " + m + " to be delivered to " + q;
- }
- else
- {
- assertFalse("Did not expect " + m + " to be delivered to " + q, m.isInQueue(q));
- //assert !m.isInQueue(q) : "Did not expect " + m + " to be delivered to " + q;
- }
- }
- }
-
- catch (NoRouteException ex)
- {
- assertTrue("Expected "+m+" not to be returned",expectReturn);
- }
-
- }
-
- static FieldTable getHeaders(String... entries)
- {
- FieldTable headers = FieldTableFactory.newFieldTable();
- for (String s : entries)
- {
- String[] parts = s.split("=", 2);
- headers.put(parts[0], parts.length > 1 ? parts[1] : "");
- }
- return headers;
- }
-
- static class TestQueue extends AMQQueue
- {
- final List<HeadersExchangeTest.Message> messages = new ArrayList<HeadersExchangeTest.Message>();
-
- public TestQueue(String name) throws AMQException
- {
- super(name, false, "test", true, ApplicationRegistry.getInstance().getQueueRegistry());
- }
-
- public void deliver(AMQMessage msg) throws AMQException
- {
- messages.add(new HeadersExchangeTest.Message(msg));
- }
- }
-
- /**
- * Just add some extra utility methods to AMQMessage to aid testing.
- */
- static class Message extends AMQMessage
- {
- private static MessageStore _messageStore = new SkeletonMessageStore();
-
- Message(String id, String... headers) throws AMQException
- {
- this(id, getHeaders(headers));
- }
-
- Message(String id, FieldTable headers) throws AMQException
- {
- this(_messageStore, getMessageTransferBody(id,headers), new ArrayList());
- }
-
- private static MessageTransferBody getMessageTransferBody(String id,FieldTable headers){
- MessageHeaders messageHeaders = new MessageHeaders();
- MessageTransferBody methodBody = MessageTransferBody.createMethodBody(
- (byte)0, (byte)9, // AMQP version (major, minor)
- messageHeaders.getAppId(), // String appId
- headers, // FieldTable applicationHeaders
- new Content(), // Content body
- messageHeaders.getEncoding(), // String contentEncoding
- messageHeaders.getContentType(), // String contentType
- messageHeaders.getCorrelationId(), // String correlationId
- (short)1, // short deliveryMode
- "someExchange", // String destination
- "someExchange", // String exchange
- messageHeaders.getExpiration(), // long expiration
- false, // boolean immediate
- false, // boolean mandatory
- null, // String messageId
- (short)0, // short priority
- false, // boolean redelivered
- messageHeaders.getReplyTo(), // String replyTo
- id, // String routingKey
- new String("abc123").getBytes(), // byte[] securityToken
- 0, // int ticket
- messageHeaders.getTimestamp(), // long timestamp
- messageHeaders.getTransactionId(), // String transactionId
- 0, // long ttl
- messageHeaders.getUserId()); // String userId
-
- return methodBody;
- }
-
- Message(MessageStore store, MessageTransferBody transferBody, List<ByteBuffer> contents) throws AMQException
- {
- super(_messageStore, transferBody, contents);
- }
-
- private Message(AMQMessage msg) throws AMQException
- {
- super(msg);
- }
-
- void route(Exchange exchange) throws AMQException
- {
- exchange.route(this);
- }
-
- boolean isInQueue(TestQueue queue)
- {
- return queue.messages.contains(this);
- }
-
- public int hashCode()
- {
- return getKey().hashCode();
- }
-
- public boolean equals(Object o)
- {
- return o instanceof HeadersExchangeTest.Message && equals((HeadersExchangeTest.Message) o);
- }
-
- private boolean equals(HeadersExchangeTest.Message m)
- {
- return getKey().equals(m.getKey());
- }
-
- public String toString()
- {
- return getKey().toString();
- }
-
- private Object getKey()
- {
- return this.getTransferBody().getRoutingKey();
- }
- }
-}
diff --git a/java/systests/src/test/java/org/apache/qpid/server/queue/ConcurrentDeliveryManagerTest.java b/java/systests/src/test/java/org/apache/qpid/server/queue/ConcurrentDeliveryManagerTest.java
deleted file mode 100644
index 3072d44f48..0000000000
--- a/java/systests/src/test/java/org/apache/qpid/server/queue/ConcurrentDeliveryManagerTest.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.queue;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.server.queue.ConcurrentDeliveryManager;
-import org.apache.qpid.server.queue.AMQQueue;
-import org.apache.qpid.server.queue.DefaultQueueRegistry;
-import org.apache.qpid.server.queue.DeliveryManagerTest;
-
-public class ConcurrentDeliveryManagerTest extends DeliveryManagerTest
-{
- public ConcurrentDeliveryManagerTest() throws Exception
- {
- try
- {
- System.setProperty("concurrentdeliverymanager","true");
- _mgr = new ConcurrentDeliveryManager(_subscriptions, new AMQQueue("myQ", false, "guest", false,
- new DefaultQueueRegistry()));
- }
- catch (Throwable t)
- {
- t.printStackTrace();
- throw new AMQException("Could not initialise delivery manager", t);
- }
- }
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(ConcurrentDeliveryManagerTest.class);
- }
-}
diff --git a/java/systests/src/test/java/org/apache/qpid/server/queue/MessageTestHelper.java b/java/systests/src/test/java/org/apache/qpid/server/queue/MessageTestHelper.java
deleted file mode 100644
index 3eba217903..0000000000
--- a/java/systests/src/test/java/org/apache/qpid/server/queue/MessageTestHelper.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.queue;
-
-import java.util.ArrayList;
-
-import junit.framework.TestCase;
-
-import org.apache.qpid.AMQException;
-import org.apache.qpid.client.message.MessageHeaders;
-import org.apache.qpid.framing.Content;
-import org.apache.qpid.framing.MessageTransferBody;
-import org.apache.qpid.server.registry.ApplicationRegistry;
-import org.apache.qpid.server.store.MessageStore;
-import org.apache.qpid.server.store.SkeletonMessageStore;
-import org.apache.qpid.server.util.TestApplicationRegistry;
-
-class MessageTestHelper extends TestCase
-{
- private final MessageStore _messageStore = new SkeletonMessageStore();
-
- MessageTestHelper() throws Exception
- {
- ApplicationRegistry.initialise(new TestApplicationRegistry());
- }
-
- AMQMessage message() throws AMQException
- {
- return message(false);
- }
-
- AMQMessage message(boolean immediate) throws AMQException
- {
- // AMQP version change: Hardwire the version to 0-9 (major=0, minor=9)
- // TODO: Establish some way to determine the version for the test.
- MessageHeaders messageHeaders = new MessageHeaders();
-
- MessageTransferBody methodBody = MessageTransferBody.createMethodBody(
- (byte)0, (byte)9, // AMQP version (major, minor)
- messageHeaders.getAppId(), // String appId
- messageHeaders.getJMSHeaders(), // FieldTable applicationHeaders
- new Content(), // Content body
- messageHeaders.getEncoding(), // String contentEncoding
- messageHeaders.getContentType(), // String contentType
- messageHeaders.getCorrelationId(), // String correlationId
- (short)1, // short deliveryMode
- "someExchange", // String destination
- "someExchange", // String exchange
- messageHeaders.getExpiration(), // long expiration
- immediate, // boolean immediate
- false, // boolean mandatory
- "", // String messageId
- (short)0, // short priority
- false, // boolean redelivered
- messageHeaders.getReplyTo(), // String replyTo
- "rk", // String routingKey
- new String("abc123").getBytes(), // byte[] securityToken
- 0, // int ticket
- messageHeaders.getTimestamp(), // long timestamp
- messageHeaders.getTransactionId(), // String transactionId
- 0, // long ttl
- messageHeaders.getUserId()); // String userId
-
- return new AMQMessage(_messageStore, methodBody, new ArrayList());
- }
-
-}
diff --git a/java/systests/src/test/java/org/apache/qpid/server/queue/SynchronizedDeliveryManagerTest.java b/java/systests/src/test/java/org/apache/qpid/server/queue/SynchronizedDeliveryManagerTest.java
deleted file mode 100644
index ebe8e192a0..0000000000
--- a/java/systests/src/test/java/org/apache/qpid/server/queue/SynchronizedDeliveryManagerTest.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.queue;
-
-import org.apache.qpid.server.queue.SynchronizedDeliveryManager;
-import org.apache.qpid.server.queue.AMQQueue;
-import org.apache.qpid.server.queue.DefaultQueueRegistry;
-import org.apache.qpid.server.queue.DeliveryManagerTest;
-import org.apache.qpid.AMQException;
-
-import junit.framework.TestSuite;
-
-public class SynchronizedDeliveryManagerTest extends DeliveryManagerTest
-{
- public SynchronizedDeliveryManagerTest() throws Exception
- {
- try
- {
- System.setProperty("concurrentdeliverymanager","false");
- _mgr = new SynchronizedDeliveryManager(_subscriptions, new AMQQueue("myQ", false, "guest", false,
- new DefaultQueueRegistry()));
- }
- catch (Throwable t)
- {
- t.printStackTrace();
- throw new AMQException("Could not initialise delivery manager", t);
- }
- }
-
- public static junit.framework.Test suite()
- {
- TestSuite suite = new TestSuite();
- suite.addTestSuite(SynchronizedDeliveryManagerTest.class);
- return suite;
- }
-}
diff --git a/java/systests/src/test/java/org/apache/qpid/server/store/TestReferenceCounting.java b/java/systests/src/test/java/org/apache/qpid/server/store/TestReferenceCounting.java
deleted file mode 100644
index f162506fed..0000000000
--- a/java/systests/src/test/java/org/apache/qpid/server/store/TestReferenceCounting.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.store;
-
-import org.apache.qpid.server.queue.AMQMessage;
-import org.apache.qpid.AMQException;
-
-import junit.framework.TestCase;
-
-/**
- * Tests that reference counting works correctly with AMQMessage and the message store
- */
-public class TestReferenceCounting extends TestCase
-{
- private TestableMemoryMessageStore _store;
-
- protected void setUp() throws Exception
- {
- super.setUp();
- _store = new TestableMemoryMessageStore();
- }
-
- /**
- * Check that when the reference count is decremented the message removes itself from the store
- */
- public void testMessageGetsRemoved() throws AMQException
- {
- AMQMessage message = new AMQMessage(_store, null);
- _store.put(message);
- assertTrue(_store.getMessageMap().size() == 1);
- message.decrementReference();
- assertTrue(_store.getMessageMap().size() == 0);
- }
-
- public void testMessageRemains() throws AMQException
- {
- AMQMessage message = new AMQMessage(_store, null);
- _store.put(message);
- assertTrue(_store.getMessageMap().size() == 1);
- message.incrementReference();
- message.decrementReference();
- assertTrue(_store.getMessageMap().size() == 1);
- }
-
- public static junit.framework.Test suite()
- {
- return new junit.framework.TestSuite(TestReferenceCounting.class);
- }
-}