From 4eaa4e42093e5524d9552d8fa312c214524b6bb4 Mon Sep 17 00:00:00 2001 From: Robert Godfrey Date: Sat, 10 Mar 2012 19:22:10 +0000 Subject: NO-JIRA : AMQP-1-0 sandbox updates - merge from trunk git-svn-id: https://svn.apache.org/repos/asf/qpid/branches/rg-amqp-1-0-sandbox@1299257 13f79535-47bb-0310-9956-ffa450edef68 --- .../access/config/AbstractConfiguration.java | 6 +- .../qpid/server/security/access/config/Action.java | 17 +- .../security/access/config/PlainConfiguration.java | 2 +- .../server/security/access/config/RuleSet.java | 4 +- .../security/access/plugins/AccessControl.java | 2 +- .../access/plugins/AccessControlActivator.java | 3 +- .../access/plugins/AccessControlConfiguration.java | 2 +- .../security/access/plugins/AccessControlTest.java | 220 ++++- .../broker-plugins/experimental/info/MANIFEST.MF | 16 - .../experimental/info/build.properties | 31 - .../broker-plugins/experimental/info/build.xml | 39 - .../main/java/org/apache/qpid/info/Activator.java | 211 ----- .../main/java/org/apache/qpid/info/AppInfo.java | 92 -- .../src/main/java/org/apache/qpid/info/Info.java | 143 --- .../java/org/apache/qpid/info/InfoService.java | 30 - .../java/org/apache/qpid/info/InfoServiceImpl.java | 66 -- .../main/java/org/apache/qpid/info/SystemInfo.java | 91 -- .../java/org/apache/qpid/info/util/HttpPoster.java | 130 --- .../org/apache/qpid/info/util/IniFileReader.java | 193 ----- .../java/org/apache/qpid/info/util/SoapClient.java | 155 ---- .../java/org/apache/qpid/info/util/XMLWriter.java | 100 --- .../apache/qpid/info/systest/InfoPluginTest.java | 277 ------ .../org/apache/qpid/info/test/HttpPosterTest.java | 107 --- .../apache/qpid/info/test/InfoServiceImplTest.java | 63 -- .../org/apache/qpid/info/test/InfoServlet.java | 57 -- .../java/org/apache/qpid/info/test/InfoTest.java | 112 --- .../apache/qpid/info/test/IniFileReaderTest.java | 136 --- .../org/apache/qpid/info/test/SoapClientTest.java | 208 ----- .../org/apache/qpid/info/test/SystemInfoTest.java | 56 -- .../org/apache/qpid/info/test/XMLWriterTest.java | 132 --- .../org/apache/qpid/shutdown/ShutdownMBean.java | 8 +- .../shutdown/src/main/java/shutdown.bnd | 2 +- .../java/org/apache/qpid/extras/Activator.java | 5 +- .../exchanges/diagnostic/DiagnosticExchange.java | 25 +- .../extras/exchanges/example/TestExchange.java | 15 +- .../org/apache/qpid/server/plugins/ExtrasTest.java | 3 +- .../security/access/config/FirewallRule.java | 7 +- .../server/security/access/plugins/Firewall.java | 9 +- .../security/access/plugins/FirewallActivator.java | 3 +- .../access/plugins/FirewallConfiguration.java | 17 +- .../security/access/FirewallConfigurationTest.java | 12 +- .../server/security/access/FirewallPluginTest.java | 15 +- qpid/java/broker/bin/create-example-ssl-stores.bat | 36 - qpid/java/broker/bin/create-example-ssl-stores.sh | 38 - qpid/java/broker/bin/qpid-passwd | 6 +- qpid/java/broker/build.xml | 9 +- qpid/java/broker/etc/broker_example.acl | 25 +- qpid/java/broker/etc/config.xml | 6 +- .../java/broker/src/main/grammar/SelectorParser.jj | 621 ------------- qpid/java/broker/src/main/java/broker.bnd | 2 +- .../apache/log4j/QpidCompositeRollingAppender.java | 209 +++-- .../apache/log4j/xml/QpidLog4JConfigurator.java | 20 +- .../apache/qpid/configuration/Configuration.java | 188 ---- .../org/apache/qpid/qmf/ManagementExchange.java | 7 +- .../apache/qpid/qmf/QMFBrokerRequestCommand.java | 13 +- .../apache/qpid/qmf/QMFBrokerResponseCommand.java | 1 - .../main/java/org/apache/qpid/qmf/QMFClass.java | 6 +- .../apache/qpid/qmf/QMFClassIndicationCommand.java | 2 - .../org/apache/qpid/qmf/QMFClassQueryCommand.java | 10 +- .../qpid/qmf/QMFCommandCompletionCommand.java | 2 - .../java/org/apache/qpid/qmf/QMFEventCommand.java | 2 - .../org/apache/qpid/qmf/QMFGetQueryCommand.java | 16 +- .../main/java/org/apache/qpid/qmf/QMFMessage.java | 6 +- .../main/java/org/apache/qpid/qmf/QMFMethod.java | 4 +- .../apache/qpid/qmf/QMFMethodRequestCommand.java | 10 +- .../main/java/org/apache/qpid/qmf/QMFPackage.java | 2 +- .../qpid/qmf/QMFPackageIndicationCommand.java | 2 - .../apache/qpid/qmf/QMFPackageQueryCommand.java | 10 +- .../main/java/org/apache/qpid/qmf/QMFProperty.java | 5 +- .../apache/qpid/qmf/QMFSchemaRequestCommand.java | 13 +- .../apache/qpid/qmf/QMFSchemaResponseCommand.java | 2 - .../main/java/org/apache/qpid/qmf/QMFService.java | 293 +++++++ .../apache/qpid/server/AMQBrokerManagerMBean.java | 33 +- .../java/org/apache/qpid/server/AMQChannel.java | 125 +-- .../main/java/org/apache/qpid/server/Broker.java | 181 ++-- .../java/org/apache/qpid/server/BrokerOptions.java | 19 +- .../qpid/server/ExtractResendAndRequeue.java | 7 +- .../src/main/java/org/apache/qpid/server/Main.java | 135 +-- .../qpid/server/ack/UnacknowledgedMessageMap.java | 7 +- .../server/ack/UnacknowledgedMessageMapImpl.java | 6 +- .../org/apache/qpid/server/binding/Binding.java | 2 +- .../apache/qpid/server/binding/BindingFactory.java | 10 +- .../server/configuration/BindingConfigType.java | 8 +- .../server/configuration/BridgeConfigType.java | 7 +- .../server/configuration/BrokerConfigType.java | 5 +- .../qpid/server/configuration/ConfigStore.java | 2 +- .../server/configuration/ConfigurationManager.java | 11 +- .../server/configuration/ConnectionConfigType.java | 7 +- .../server/configuration/ExchangeConfigType.java | 8 +- .../qpid/server/configuration/LinkConfig.java | 5 - .../qpid/server/configuration/LinkConfigType.java | 7 +- .../qpid/server/configuration/QueueConfig.java | 4 +- .../qpid/server/configuration/QueueConfigType.java | 8 +- .../server/configuration/QueueConfiguration.java | 7 +- .../server/configuration/ServerConfiguration.java | 96 ++- .../ServerNetworkTransportConfiguration.java | 18 +- .../server/configuration/SessionConfigType.java | 7 +- .../configuration/SubscriptionConfigType.java | 6 +- .../server/configuration/SystemConfigImpl.java | 6 +- .../server/configuration/SystemConfigType.java | 6 +- .../qpid/server/configuration/TopicConfig.java | 5 +- .../server/configuration/TopicConfiguration.java | 17 +- .../configuration/VirtualHostConfigType.java | 5 +- .../configuration/VirtualHostConfiguration.java | 42 +- .../management/ConfigurationManagementMBean.java | 5 +- .../configuration/plugins/ConfigurationPlugin.java | 39 +- .../plugins/ConfigurationPluginFactory.java | 4 +- .../SlowConsumerDetectionConfiguration.java | 5 +- .../SlowConsumerDetectionPolicyConfiguration.java | 2 - .../SlowConsumerDetectionQueueConfiguration.java | 3 +- .../qpid/server/connection/ConnectionRegistry.java | 10 +- .../server/connection/IConnectionRegistry.java | 4 +- .../qpid/server/exchange/AbstractExchange.java | 9 +- .../server/exchange/AbstractExchangeMBean.java | 77 +- .../server/exchange/DefaultExchangeFactory.java | 13 +- .../server/exchange/DefaultExchangeRegistry.java | 30 +- .../qpid/server/exchange/DirectExchangeMBean.java | 16 +- .../org/apache/qpid/server/exchange/Exchange.java | 11 +- .../qpid/server/exchange/ExchangeFactory.java | 4 +- .../qpid/server/exchange/ExchangeRegistry.java | 2 +- .../apache/qpid/server/exchange/ExchangeType.java | 2 +- .../qpid/server/exchange/FanoutExchangeMBean.java | 12 +- .../qpid/server/exchange/HeadersBinding.java | 63 +- .../qpid/server/exchange/HeadersExchange.java | 41 +- .../qpid/server/exchange/HeadersExchangeMBean.java | 40 +- .../apache/qpid/server/exchange/MessageRouter.java | 40 - .../apache/qpid/server/exchange/TopicExchange.java | 232 ++++- .../qpid/server/exchange/TopicExchangeMBean.java | 16 +- .../qpid/server/exchange/headers/HeaderKey.java | 40 - .../exchange/headers/HeaderKeyDictionary.java | 50 -- .../exchange/headers/HeaderMatcherResult.java | 25 - .../exchange/headers/HeadersMatcherDFAState.java | 339 -------- .../server/exchange/headers/HeadersParser.java | 315 ------- .../server/exchange/topic/TopicExchangeResult.java | 2 +- .../exchange/topic/TopicMatcherDFAState.java | 25 +- .../server/exchange/topic/TopicNormalizer.java | 7 +- .../qpid/server/exchange/topic/TopicParser.java | 256 ++---- .../qpid/server/exchange/topic/TopicWord.java | 4 - .../org/apache/qpid/server/federation/Bridge.java | 27 +- .../apache/qpid/server/federation/BrokerLink.java | 21 +- .../qpid/server/filter/ArithmeticExpression.java | 275 ------ .../qpid/server/filter/BinaryExpression.java | 106 --- .../qpid/server/filter/BooleanExpression.java | 38 - .../qpid/server/filter/ComparisonExpression.java | 599 ------------- .../qpid/server/filter/ConstantExpression.java | 209 ----- .../org/apache/qpid/server/filter/Expression.java | 36 - .../qpid/server/filter/FilterManagerFactory.java | 30 +- .../qpid/server/filter/JMSSelectorFilter.java | 70 +- .../apache/qpid/server/filter/LogicExpression.java | 120 --- .../qpid/server/filter/NoConsumerFilter.java | 1 + .../qpid/server/filter/PropertyExpression.java | 236 ----- .../qpid/server/filter/SimpleFilterManager.java | 6 +- .../apache/qpid/server/filter/UnaryExpression.java | 362 -------- .../apache/qpid/server/filter/XPathExpression.java | 126 --- .../qpid/server/filter/XQueryExpression.java | 57 -- .../qpid/server/filter/XalanXPathEvaluator.java | 101 --- .../server/flow/AbstractFlowCreditManager.java | 4 +- .../qpid/server/flow/CreditCreditManager.java | 15 +- .../qpid/server/flow/Pre0_10CreditManager.java | 2 - .../qpid/server/flow/WindowCreditManager.java | 2 - .../qpid/server/handler/AccessRequestHandler.java | 14 +- .../qpid/server/handler/BasicAckMethodHandler.java | 2 +- .../server/handler/BasicCancelMethodHandler.java | 3 +- .../server/handler/BasicConsumeMethodHandler.java | 6 +- .../qpid/server/handler/BasicGetMethodHandler.java | 14 +- .../server/handler/BasicPublishMethodHandler.java | 1 + .../qpid/server/handler/BasicQosHandler.java | 4 +- .../server/handler/BasicRecoverMethodHandler.java | 5 +- .../handler/BasicRecoverSyncMethodHandler.java | 14 +- .../server/handler/BasicRejectMethodHandler.java | 5 +- .../qpid/server/handler/ChannelCloseHandler.java | 5 +- .../qpid/server/handler/ChannelCloseOkHandler.java | 2 +- .../qpid/server/handler/ChannelFlowHandler.java | 6 +- .../qpid/server/handler/ChannelOpenHandler.java | 11 +- .../handler/ConnectionCloseMethodHandler.java | 3 +- .../handler/ConnectionCloseOkMethodHandler.java | 2 +- .../handler/ConnectionOpenMethodHandler.java | 1 + .../handler/ConnectionSecureOkMethodHandler.java | 6 +- .../handler/ConnectionStartOkMethodHandler.java | 12 +- .../handler/ConnectionTuneOkMethodHandler.java | 1 + .../qpid/server/handler/ExchangeBoundHandler.java | 7 +- .../server/handler/ExchangeDeclareHandler.java | 34 +- .../qpid/server/handler/QueueDeclareHandler.java | 12 +- .../qpid/server/handler/QueueDeleteHandler.java | 6 +- .../qpid/server/handler/QueuePurgeHandler.java | 8 +- .../qpid/server/handler/QueueUnbindHandler.java | 1 + .../server/handler/ServerMethodDispatcherImpl.java | 10 +- .../handler/ServerMethodDispatcherImpl_0_9.java | 4 +- .../handler/ServerMethodDispatcherImpl_0_91.java | 2 +- .../handler/ServerMethodDispatcherImpl_8_0.java | 13 +- .../qpid/server/handler/TxCommitHandler.java | 5 +- .../qpid/server/handler/TxRollbackHandler.java | 6 +- .../qpid/server/handler/TxSelectHandler.java | 5 +- .../server/handler/UnexpectedMethodException.java | 2 +- .../management/ServerInformationMBean.java | 3 +- .../qpid/server/logging/Log4jMessageLogger.java | 1 + .../server/logging/actors/AMQPChannelActor.java | 3 - .../qpid/server/logging/actors/AbstractActor.java | 4 +- .../qpid/server/logging/actors/CurrentActor.java | 4 + .../qpid/server/logging/actors/GenericActor.java | 1 - .../server/logging/actors/ManagementActor.java | 7 +- .../qpid/server/logging/actors/QueueActor.java | 2 - .../logging/management/LoggingManagementMBean.java | 37 +- .../logging/messages/Broker_logmessages.properties | 14 +- .../messages/Connection_logmessages.properties | 3 +- .../messages/TransactionLog_logmessages.properties | 6 + .../logging/subjects/AbstractLogSubject.java | 17 +- .../server/logging/subjects/BindingLogSubject.java | 1 + .../server/logging/subjects/ChannelLogSubject.java | 6 +- .../logging/subjects/ConnectionLogSubject.java | 30 +- .../logging/subjects/ExchangeLogSubject.java | 1 + .../server/logging/subjects/LogSubjectFormat.java | 5 +- .../logging/subjects/MessageStoreLogSubject.java | 3 +- .../server/logging/subjects/QueueLogSubject.java | 1 + .../logging/subjects/SubscriptionLogSubject.java | 8 +- .../qpid/server/management/AMQManagedObject.java | 49 +- .../AbstractAMQManagedConnectionObject.java | 11 +- .../server/management/DefaultManagedObject.java | 11 +- .../management/JMXManagedObjectRegistry.java | 62 +- .../qpid/server/management/MBeanIntrospector.java | 33 +- .../management/MBeanInvocationHandlerImpl.java | 41 +- .../qpid/server/management/ManagedObject.java | 6 +- .../server/management/ManagedObjectRegistry.java | 5 +- .../management/NoopManagedObjectRegistry.java | 4 +- .../org/apache/qpid/server/message/AMQMessage.java | 19 +- .../qpid/server/message/AMQMessageReference.java | 3 - .../server/message/AbstractServerMessageImpl.java | 5 +- .../server/message/ContentHeaderBodyAdapter.java | 2 +- .../apache/qpid/server/message/InboundMessage.java | 2 +- .../qpid/server/message/MessageMetaData.java | 14 +- .../qpid/server/message/MessageMetaData_0_10.java | 22 +- .../qpid/server/message/MessageTransferHeader.java | 4 +- .../server/message/MessageTransferMessage.java | 6 +- .../apache/qpid/server/message/ServerMessage.java | 4 +- .../server/output/HeaderPropertiesConverter.java | 17 +- .../server/output/ProtocolOutputConverter.java | 10 +- .../server/output/ProtocolOutputConverterImpl.java | 413 +++++++++ .../output/ProtocolOutputConverterRegistry.java | 43 +- .../amqp0_8/ProtocolOutputConverterImpl.java | 420 --------- .../amqp0_9/ProtocolOutputConverterImpl.java | 418 --------- .../amqp0_9_1/ProtocolOutputConverterImpl.java | 425 --------- .../org/apache/qpid/server/plugins/Activator.java | 5 +- .../qpid/server/plugins/OsgiSystemPackageUtil.java | 4 +- .../org/apache/qpid/server/plugins/Plugin.java | 1 + .../apache/qpid/server/plugins/PluginFactory.java | 1 + .../apache/qpid/server/plugins/PluginManager.java | 66 +- .../qpid/server/protocol/AMQConnectionModel.java | 6 +- .../qpid/server/protocol/AMQProtocolEngine.java | 276 +----- .../qpid/server/protocol/AMQProtocolSession.java | 43 +- .../server/protocol/AMQProtocolSessionMBean.java | 31 +- .../qpid/server/protocol/AMQSessionModel.java | 13 +- .../protocol/MultiVersionProtocolEngine.java | 86 +- .../MultiVersionProtocolEngineFactory.java | 26 +- .../qpid/server/protocol/ProtocolEngine_0_10.java | 18 +- .../qpid/server/protocol/v1_0/SendingLink_1_0.java | 4 +- .../apache/qpid/server/queue/AMQPriorityQueue.java | 5 +- .../org/apache/qpid/server/queue/AMQQueue.java | 13 +- .../apache/qpid/server/queue/AMQQueueFactory.java | 9 +- .../apache/qpid/server/queue/AMQQueueMBean.java | 50 +- .../org/apache/qpid/server/queue/BaseQueue.java | 4 +- .../apache/qpid/server/queue/ConflationQueue.java | 2 +- .../qpid/server/queue/ConflationQueueList.java | 6 +- .../org/apache/qpid/server/queue/Filterable.java | 2 - .../qpid/server/queue/InboundMessageAdapter.java | 4 +- .../apache/qpid/server/queue/IncomingMessage.java | 64 +- .../qpid/server/queue/NotificationCheck.java | 1 - .../apache/qpid/server/queue/OutOfOrderQueue.java | 10 +- .../qpid/server/queue/PriorityQueueList.java | 2 +- .../org/apache/qpid/server/queue/QueueContext.java | 10 +- .../org/apache/qpid/server/queue/QueueEntry.java | 4 +- .../apache/qpid/server/queue/QueueEntryImpl.java | 13 +- .../apache/qpid/server/queue/QueueRegistry.java | 1 - .../org/apache/qpid/server/queue/QueueRunner.java | 47 +- .../apache/qpid/server/queue/SimpleAMQQueue.java | 243 +++--- .../qpid/server/queue/SimpleQueueEntryImpl.java | 9 +- .../qpid/server/queue/SimpleQueueEntryList.java | 82 +- .../org/apache/qpid/server/queue/SortedQueue.java | 3 +- .../qpid/server/queue/SortedQueueEntryList.java | 7 +- .../apache/qpid/server/queue/SubFlushRunner.java | 36 +- .../qpid/server/registry/ApplicationRegistry.java | 289 +++++-- .../qpid/server/registry/BrokerConfigAdapter.java | 11 +- .../ConfigurationFileApplicationRegistry.java | 31 +- .../qpid/server/registry/IApplicationRegistry.java | 8 +- .../qpid/server/security/AbstractPlugin.java | 10 +- .../qpid/server/security/AbstractProxyPlugin.java | 3 - .../qpid/server/security/AuthorizationHolder.java | 10 +- .../qpid/server/security/SecurityManager.java | 40 +- .../server/security/SecurityPluginActivator.java | 3 +- .../server/security/access/ObjectProperties.java | 27 +- .../qpid/server/security/access/ObjectType.java | 10 +- .../server/security/access/plugins/AllowAll.java | 99 --- .../security/access/plugins/BasicPlugin.java | 4 +- .../server/security/access/plugins/DenyAll.java | 99 --- .../security/access/plugins/LegacyAccess.java | 17 +- .../server/security/auth/AuthenticationResult.java | 4 +- .../AbstractPasswordFilePrincipalDatabase.java | 484 +++++++++++ .../Base64MD5PasswordFilePrincipalDatabase.java | 475 +--------- .../server/security/auth/database/HashedUser.java | 55 +- .../security/auth/database/PasswordPrincipal.java | 40 + .../PlainPasswordFilePrincipalDatabase.java | 452 +--------- .../server/security/auth/database/PlainUser.java | 19 +- .../security/auth/database/PrincipalDatabase.java | 8 +- .../auth/database/PropertiesPrincipalDatabase.java | 12 +- .../auth/management/AMQUserManagementMBean.java | 22 +- .../auth/manager/AuthenticationManager.java | 9 +- .../PrincipalDatabaseAuthenticationManager.java | 50 +- .../auth/rmi/RMIPasswordAuthenticator.java | 8 +- .../sasl/AuthenticationProviderInitialiser.java | 3 +- .../server/security/auth/sasl/JCAProvider.java | 3 +- .../auth/sasl/UsernamePasswordInitialiser.java | 18 +- .../security/auth/sasl/UsernamePrincipal.java | 3 +- .../auth/sasl/amqplain/AmqPlainInitialiser.java | 4 +- .../auth/sasl/amqplain/AmqPlainSaslServer.java | 13 +- .../sasl/amqplain/AmqPlainSaslServerFactory.java | 3 +- .../auth/sasl/anonymous/AnonymousInitialiser.java | 40 +- .../sasl/anonymous/AnonymousSaslServerFactory.java | 5 +- .../sasl/crammd5/CRAMMD5HashedInitialiser.java | 2 +- .../auth/sasl/crammd5/CRAMMD5HashedSaslServer.java | 6 +- .../sasl/crammd5/CRAMMD5HashedServerFactory.java | 3 +- .../auth/sasl/crammd5/CRAMMD5HexInitialiser.java | 10 +- .../auth/sasl/crammd5/CRAMMD5HexSaslServer.java | 6 +- .../auth/sasl/crammd5/CRAMMD5HexServerFactory.java | 3 +- .../auth/sasl/crammd5/CRAMMD5Initialiser.java | 2 +- .../security/auth/sasl/plain/PlainInitialiser.java | 4 +- .../auth/sasl/plain/PlainPasswordCallback.java | 3 +- .../security/auth/sasl/plain/PlainSaslServer.java | 68 +- .../auth/sasl/plain/PlainSaslServerFactory.java | 3 +- .../qpid/server/signal/SignalHandlerTask.java | 4 +- .../apache/qpid/server/state/AMQStateManager.java | 136 +-- .../server/state/StateAwareMethodListener.java | 1 - .../qpid/server/stats/StatisticsCounter.java | 6 +- .../qpid/server/store/AbstractMessageStore.java | 6 +- .../server/store/ConfigurationRecoveryHandler.java | 4 +- .../qpid/server/store/DerbyMessageStore.java | 420 ++++++++- .../server/store/DurableConfigurationStore.java | 1 + .../qpid/server/store/MemoryMessageStore.java | 18 +- .../org/apache/qpid/server/store/MessageStore.java | 11 +- .../server/store/MessageStoreClosedException.java | 8 +- .../store/TransactionLogRecoveryHandler.java | 9 +- .../AssignedSubscriptionMessageGroupManager.java | 14 +- .../server/subscription/ClientDeliveryMethod.java | 2 +- .../DefinedGroupMessageGroupManager.java | 7 +- .../ExplicitAcceptDispositionChangeListener.java | 5 +- .../ImplicitAcceptDispositionChangeListener.java | 7 +- .../qpid/server/subscription/Subscription.java | 1 - .../server/subscription/SubscriptionFactory.java | 9 +- .../subscription/SubscriptionFactoryImpl.java | 6 +- .../qpid/server/subscription/SubscriptionImpl.java | 22 +- .../qpid/server/subscription/SubscriptionList.java | 4 +- .../server/subscription/Subscription_0_10.java | 100 +-- .../apache/qpid/server/transport/QpidAcceptor.java | 4 +- .../qpid/server/transport/ServerConnection.java | 51 +- .../server/transport/ServerConnectionDelegate.java | 91 +- .../server/transport/ServerConnectionMBean.java | 27 +- .../qpid/server/transport/ServerSession.java | 190 +++- .../server/transport/ServerSessionDelegate.java | 427 +++++++-- .../qpid/server/txn/AlreadyKnownDtxException.java | 32 + .../server/txn/AsyncAutoCommitTransaction.java | 1 + .../qpid/server/txn/AutoCommitTransaction.java | 8 +- .../qpid/server/txn/DistributedTransaction.java | 246 ++++++ .../java/org/apache/qpid/server/txn/DtxBranch.java | 348 ++++++++ .../org/apache/qpid/server/txn/DtxException.java | 44 + .../qpid/server/txn/DtxNotSelectedException.java | 30 + .../org/apache/qpid/server/txn/DtxRegistry.java | 333 +++++++ .../server/txn/IncorrectDtxStateException.java | 32 + .../qpid/server/txn/JoinAndResumeDtxException.java | 32 + .../apache/qpid/server/txn/LocalTransaction.java | 10 +- .../qpid/server/txn/NotAssociatedDtxException.java | 32 + .../qpid/server/txn/RollbackOnlyDtxException.java | 32 + .../server/txn/SuspendAndFailDtxException.java | 32 + .../qpid/server/txn/TimeoutDtxException.java | 32 + .../qpid/server/txn/UnknownDtxBranchException.java | 32 + .../apache/qpid/server/util/CircularBuffer.java | 131 --- .../org/apache/qpid/server/util/LoggingProxy.java | 105 --- .../qpid/server/virtualhost/HouseKeepingTask.java | 5 +- .../server/virtualhost/ManagedVirtualHost.java | 4 +- .../qpid/server/virtualhost/VirtualHost.java | 10 +- .../VirtualHostConfigRecoveryHandler.java | 238 ++++- .../qpid/server/virtualhost/VirtualHostImpl.java | 172 ++-- .../server/virtualhost/VirtualHostRegistry.java | 2 +- .../plugins/ConfiguredQueueBindingListener.java | 13 +- .../virtualhost/plugins/SlowConsumerDetection.java | 29 +- .../plugins/VirtualHostHouseKeepingPlugin.java | 9 +- .../virtualhost/plugins/VirtualHostPlugin.java | 5 +- .../plugins/policies/TopicDeletePolicy.java | 4 +- .../policies/TopicDeletePolicyConfiguration.java | 7 +- .../org/apache/qpid/tools/security/Passwd.java | 9 +- .../log4j/xml/QpidLog4JConfiguratorTest.java | 7 +- .../qpid/server/AMQBrokerManagerMBeanTest.java | 9 +- .../org/apache/qpid/server/BrokerOptionsTest.java | 4 +- .../qpid/server/ExtractResendAndRequeueTest.java | 19 +- .../test/java/org/apache/qpid/server/MainTest.java | 26 +- .../org/apache/qpid/server/SelectorParserTest.java | 26 +- .../configuration/QueueConfigurationTest.java | 1 + .../configuration/ServerConfigurationTest.java | 99 ++- .../configuration/TopicConfigurationTest.java | 1 + .../VirtualHostConfigurationTest.java | 1 + .../plugins/ConfigurationPluginTest.java | 4 +- .../exchange/AbstractHeadersExchangeTestBase.java | 36 +- .../qpid/server/exchange/ExchangeMBeanTest.java | 9 +- .../qpid/server/exchange/HeadersBindingTest.java | 10 +- .../qpid/server/exchange/HeadersExchangeTest.java | 6 +- .../qpid/server/exchange/TopicExchangeTest.java | 39 +- .../qpid/server/flow/WindowCreditManagerTest.java | 2 +- .../server/logging/Log4jMessageLoggerTest.java | 16 +- .../apache/qpid/server/logging/LogMessageTest.java | 1 + .../qpid/server/logging/UnitTestMessageLogger.java | 5 +- .../logging/actors/AMQPChannelActorTest.java | 5 +- .../server/logging/actors/BaseActorTestCase.java | 3 +- .../server/logging/actors/CurrentActorTest.java | 11 +- .../server/logging/actors/ManagementActorTest.java | 5 +- .../logging/actors/SubscriptionActorTest.java | 4 +- .../management/LoggingManagementMBeanTest.java | 19 +- .../logging/messages/AbstractTestMessages.java | 20 +- .../logging/messages/BrokerMessagesTest.java | 33 +- .../logging/messages/ConnectionMessagesTest.java | 44 +- .../logging/subjects/AbstractTestLogSubject.java | 7 +- .../logging/subjects/ExchangeLogSubjectTest.java | 4 +- .../subjects/MessageStoreLogSubjectTest.java | 4 +- .../server/logging/subjects/TestBlankSubject.java | 2 +- .../management/AMQUserManagementMBeanTest.java | 18 +- .../server/plugins/OsgiSystemPackageUtilTest.java | 11 +- .../org/apache/qpid/server/plugins/PluginTest.java | 1 - .../protocol/AMQProtocolSessionMBeanTest.java | 8 +- .../protocol/InternalTestProtocolSession.java | 28 +- .../qpid/server/protocol/MaxChannelsTest.java | 3 +- .../MultiVersionProtocolEngineFactoryTest.java | 37 +- .../qpid/server/queue/AMQPriorityQueueTest.java | 4 +- .../qpid/server/queue/AMQQueueAlertTest.java | 21 +- .../qpid/server/queue/AMQQueueFactoryTest.java | 5 +- .../qpid/server/queue/AMQQueueMBeanTest.java | 33 +- .../java/org/apache/qpid/server/queue/AckTest.java | 26 +- .../org/apache/qpid/server/queue/MockAMQQueue.java | 21 +- .../qpid/server/queue/MockMessagePublishInfo.java | 2 +- .../apache/qpid/server/queue/MockQueueEntry.java | 4 +- .../qpid/server/queue/MockStoredMessage.java | 9 +- .../qpid/server/queue/QueueEntryImplTestBase.java | 4 +- .../qpid/server/queue/QueueEntryListTestBase.java | 34 + .../queue/SelfValidatingSortedQueueEntryList.java | 1 + .../qpid/server/queue/SimpleAMQQueueTest.java | 109 ++- .../server/queue/SimpleAMQQueueThreadPoolTest.java | 6 +- .../server/queue/SimpleQueueEntryListTest.java | 26 +- .../server/queue/SortedQueueEntryListTest.java | 20 +- .../registry/ApplicationRegistryShutdownTest.java | 11 +- ...Base64MD5PasswordFilePrincipalDatabaseTest.java | 7 +- .../security/auth/database/HashedUserTest.java | 58 +- .../PlainPasswordFilePrincipalDatabaseTest.java | 3 +- .../security/auth/database/PlainUserTest.java | 6 +- ...PrincipalDatabaseAuthenticationManagerTest.java | 22 +- .../auth/rmi/RMIPasswordAuthenticatorTest.java | 13 +- .../auth/sasl/CRAMMD5HexInitialiserTest.java | 1 + .../security/auth/sasl/CRAMMD5HexServerTest.java | 23 +- .../security/auth/sasl/SaslServerTestCase.java | 8 +- .../security/auth/sasl/TestPrincipalDatabase.java | 10 +- .../security/auth/sasl/TestPrincipalUtils.java | 3 +- .../security/auth/sasl/UsernamePrincipalTest.java | 5 +- .../qpid/server/signal/SignalHandlerTaskTest.java | 7 +- .../qpid/server/stats/StatisticsCounterTest.java | 7 +- .../apache/qpid/server/store/MessageStoreTest.java | 51 +- .../qpid/server/store/SkeletonMessageStore.java | 21 +- .../qpid/server/store/TestMemoryMessageStore.java | 8 +- .../server/store/TestableMemoryMessageStore.java | 19 +- .../qpid/server/subscription/MockSubscription.java | 20 +- .../subscription/QueueBrowserUsesNoAckTest.java | 6 +- .../transport/ServerConnectionMBeanTest.java | 19 +- .../qpid/server/txn/AutoCommitTransactionTest.java | 8 +- .../qpid/server/txn/LocalTransactionTest.java | 8 +- .../apache/qpid/server/txn/MockServerMessage.java | 5 +- .../qpid/server/txn/MockStoreTransaction.java | 17 +- .../qpid/server/util/InternalBrokerBaseCase.java | 7 +- .../apache/qpid/server/util/LoggingProxyTest.java | 88 -- .../qpid/server/util/TestApplicationRegistry.java | 7 +- .../server/virtualhost/HouseKeepingTaskTest.java | 4 +- .../qpid/server/virtualhost/MockVirtualHost.java | 18 +- .../server/virtualhost/VirtualHostImplTest.java | 11 +- .../SlowConsumerDetectionConfigurationTest.java | 1 + ...owConsumerDetectionPolicyConfigurationTest.java | 1 + ...lowConsumerDetectionQueueConfigurationTest.java | 1 + .../TopicDeletePolicyConfigurationTest.java | 1 + .../plugins/policies/TopicDeletePolicyTest.java | 7 +- .../org/apache/qpid/tools/security/PasswdTest.java | 38 + .../qpid/server/logging/GenerateLogMessages.java | 33 +- .../qpid/server/logging/messages/LogMessages.vm | 10 +- qpid/java/broker/src/xsl/qmf.xsl | 20 + qpid/java/client/README.txt | 2 - qpid/java/client/build.xml | 8 - qpid/java/client/example/src/main/java/README.txt | 33 - .../main/java/org/apache/qpid/example/Drain.java | 18 +- .../java/org/apache/qpid/example/OptionParser.java | 50 +- .../main/java/org/apache/qpid/example/Spout.java | 20 +- .../example/publisher/FileMessageDispatcher.java | 163 ---- .../qpid/example/publisher/FileMessageFactory.java | 138 --- .../example/publisher/MessageFactoryException.java | 29 - .../publisher/MonitorMessageDispatcher.java | 141 --- .../qpid/example/publisher/MonitorPublisher.java | 105 --- .../example/publisher/MultiMessageDispatcher.java | 141 --- .../apache/qpid/example/publisher/Publisher.java | 208 ----- .../qpid/example/publisher/TopicPublisher.java | 59 -- .../publisher/UndeliveredMessageException.java | 32 - .../org/apache/qpid/example/pubsub/Client.java | 72 -- .../qpid/example/pubsub/ConnectionSetup.java | 121 --- .../org/apache/qpid/example/pubsub/Publisher.java | 81 -- .../org/apache/qpid/example/pubsub/Subscriber.java | 98 --- .../qpid/example/shared/ConnectionException.java | 29 - .../qpid/example/shared/ContextException.java | 29 - .../org/apache/qpid/example/shared/FileUtils.java | 168 ---- .../qpid/example/shared/InitialContextHelper.java | 81 -- .../org/apache/qpid/example/shared/Statics.java | 57 -- .../apache/qpid/example/shared/example.properties | 40 - .../apache/qpid/example/simple/reqresp/Client.java | 263 ------ .../apache/qpid/example/simple/reqresp/Server.java | 236 ----- .../example/subscriber/MonitoredSubscriber.java | 139 --- .../subscriber/MonitoredSubscriptionWrapper.java | 47 - .../apache/qpid/example/subscriber/Subscriber.java | 182 ---- .../example/subscriber/SubscriptionWrapper.java | 46 - .../java/client/example/src/main/java/runSample.sh | 72 -- .../java/client/src/main/grammar/SelectorParser.jj | 609 ------------- qpid/java/client/src/main/java/client.bnd | 2 +- .../org/apache/qpid/client/AMQAnyDestination.java | 9 +- .../org/apache/qpid/client/AMQBrokerDetails.java | 50 +- .../java/org/apache/qpid/client/AMQConnection.java | 153 ++-- .../apache/qpid/client/AMQConnectionDelegate.java | 9 +- .../qpid/client/AMQConnectionDelegate_0_10.java | 42 +- .../qpid/client/AMQConnectionDelegate_8_0.java | 83 +- .../apache/qpid/client/AMQConnectionFactory.java | 112 ++- .../org/apache/qpid/client/AMQConnectionURL.java | 18 +- .../org/apache/qpid/client/AMQDestination.java | 132 ++- .../main/java/org/apache/qpid/client/AMQQueue.java | 14 +- .../org/apache/qpid/client/AMQQueueBrowser.java | 74 +- .../apache/qpid/client/AMQQueueSessionAdaptor.java | 167 +--- .../java/org/apache/qpid/client/AMQSession.java | 796 ++++++++--------- .../org/apache/qpid/client/AMQSessionAdapter.java | 169 +++- .../org/apache/qpid/client/AMQSession_0_10.java | 166 ++-- .../org/apache/qpid/client/AMQSession_0_8.java | 181 ++-- .../org/apache/qpid/client/AMQTemporaryQueue.java | 5 +- .../main/java/org/apache/qpid/client/AMQTopic.java | 13 +- .../apache/qpid/client/AMQTopicSessionAdaptor.java | 170 +--- .../apache/qpid/client/BasicMessageConsumer.java | 137 +-- .../qpid/client/BasicMessageConsumer_0_10.java | 74 +- .../qpid/client/BasicMessageConsumer_0_8.java | 35 +- .../apache/qpid/client/BasicMessageProducer.java | 179 +++- .../qpid/client/BasicMessageProducer_0_10.java | 50 +- .../qpid/client/BasicMessageProducer_0_8.java | 60 +- .../java/org/apache/qpid/client/Closeable.java | 14 +- .../org/apache/qpid/client/CustomJMSXProperty.java | 4 +- .../org/apache/qpid/client/DispatcherCallback.java | 36 - .../apache/qpid/client/MessageConsumerPair.java | 4 +- .../apache/qpid/client/QpidConnectionMetaData.java | 5 +- .../apache/qpid/client/QueueReceiverAdaptor.java | 4 +- .../org/apache/qpid/client/QueueSenderAdapter.java | 2 +- .../apache/qpid/client/TemporaryDestination.java | 4 +- .../org/apache/qpid/client/XAConnectionImpl.java | 14 +- .../org/apache/qpid/client/XAResourceImpl.java | 36 +- .../java/org/apache/qpid/client/XASessionImpl.java | 27 +- .../qpid/client/failover/FailoverHandler.java | 15 +- .../qpid/client/failover/FailoverNoopSupport.java | 4 +- .../qpid/client/failover/FailoverRetrySupport.java | 8 +- .../qpid/client/filter/JMSSelectorFilter.java | 4 + .../handler/AccessRequestOkMethodHandler.java | 6 +- .../client/handler/BasicCancelOkMethodHandler.java | 6 +- .../client/handler/BasicDeliverMethodHandler.java | 5 +- .../client/handler/BasicReturnMethodHandler.java | 6 +- .../client/handler/ChannelCloseMethodHandler.java | 5 +- .../handler/ChannelCloseOkMethodHandler.java | 5 +- .../client/handler/ChannelFlowMethodHandler.java | 9 +- .../client/handler/ChannelFlowOkMethodHandler.java | 6 +- .../client/handler/ClientMethodDispatcherImpl.java | 21 +- .../handler/ClientMethodDispatcherImpl_0_9.java | 8 +- .../handler/ClientMethodDispatcherImpl_0_91.java | 8 +- .../handler/ClientMethodDispatcherImpl_8_0.java | 14 +- .../handler/ConnectionCloseMethodHandler.java | 10 +- .../handler/ConnectionOpenOkMethodHandler.java | 3 +- .../handler/ConnectionRedirectMethodHandler.java | 6 +- .../handler/ConnectionSecureMethodHandler.java | 6 +- .../handler/ConnectionStartMethodHandler.java | 53 +- .../handler/ConnectionTuneMethodHandler.java | 13 +- .../handler/ExchangeBoundOkMethodHandler.java | 6 +- .../client/handler/QueueDeleteOkMethodHandler.java | 6 +- .../qpid/client/message/AMQMessageDelegate.java | 1 - .../client/message/AMQMessageDelegate_0_10.java | 100 ++- .../client/message/AMQMessageDelegate_0_8.java | 48 +- .../qpid/client/message/AMQPEncodedMapMessage.java | 31 +- .../message/AMQPEncodedMapMessageFactory.java | 5 +- .../client/message/AbstractAMQMessageDelegate.java | 23 +- .../client/message/AbstractBytesTypedMessage.java | 19 +- .../qpid/client/message/AbstractJMSMessage.java | 13 +- .../client/message/AbstractJMSMessageFactory.java | 24 +- .../qpid/client/message/FieldTableSupport.java | 52 +- .../qpid/client/message/JMSBytesMessage.java | 14 +- .../client/message/JMSBytesMessageFactory.java | 5 +- .../qpid/client/message/JMSHeaderAdapter.java | 27 +- .../apache/qpid/client/message/JMSMapMessage.java | 18 +- .../qpid/client/message/JMSMapMessageFactory.java | 4 +- .../qpid/client/message/JMSObjectMessage.java | 14 +- .../client/message/JMSObjectMessageFactory.java | 4 +- .../qpid/client/message/JMSStreamMessage.java | 9 +- .../client/message/JMSStreamMessageFactory.java | 5 +- .../apache/qpid/client/message/JMSTextMessage.java | 17 +- .../qpid/client/message/JMSTextMessageFactory.java | 6 +- .../qpid/client/message/MessageConverter.java | 13 +- .../apache/qpid/client/message/MessageFactory.java | 7 +- .../client/message/MessageFactoryRegistry.java | 20 +- .../qpid/client/message/QpidMessageProperties.java | 3 + .../client/message/TypedBytesContentReader.java | 2 +- .../qpid/client/message/UnprocessedMessage.java | 1 - .../client/message/UnprocessedMessage_0_8.java | 18 +- .../client/messaging/address/AddressHelper.java | 11 +- .../apache/qpid/client/messaging/address/Link.java | 20 +- .../apache/qpid/client/messaging/address/Node.java | 43 +- .../qpid/client/protocol/AMQProtocolHandler.java | 184 +--- .../qpid/client/protocol/AMQProtocolSession.java | 102 ++- .../protocol/BlockingMethodFrameListener.java | 7 +- .../qpid/client/protocol/HeartbeatDiagnostics.java | 4 + .../qpid/client/security/AMQCallbackHandler.java | 4 +- .../client/security/CallbackHandlerRegistry.java | 9 +- .../qpid/client/security/DynamicSaslRegistrar.java | 50 +- .../apache/qpid/client/security/JCAProvider.java | 3 - .../UsernameHashedPasswordCallbackHandler.java | 11 +- .../security/UsernamePasswordCallbackHandler.java | 5 +- .../security/amqplain/AmqPlainSaslClient.java | 6 +- .../amqplain/AmqPlainSaslClientFactory.java | 3 +- .../anonymous/AnonymousSaslClientFactory.java | 8 +- .../CRAMMD5HashedSaslClientFactory.java | 9 +- .../state/AMQMethodNotImplementedException.java | 2 +- .../apache/qpid/client/state/AMQStateManager.java | 12 +- .../client/state/StateAwareMethodListener.java | 3 +- .../org/apache/qpid/client/state/StateWaiter.java | 9 +- .../AMQNoTransportForProtocolException.java | 59 -- .../transport/AMQTransportConnectionException.java | 43 - .../client/transport/ClientConnectionDelegate.java | 32 +- .../client/transport/ITransportConnection.java | 32 - .../java/org/apache/qpid/client/url/URLParser.java | 8 +- .../org/apache/qpid/client/url/URLParser_0_10.java | 7 +- .../apache/qpid/client/util/BlockingWaiter.java | 21 +- .../client/util/FlowControllingBlockingQueue.java | 6 +- .../java/org/apache/qpid/collections/KeyValue.java | 46 - .../org/apache/qpid/collections/ReferenceMap.java | 957 --------------------- .../collections/keyvalue/AbstractKeyValue.java | 83 -- .../collections/keyvalue/AbstractMapEntry.java | 96 --- .../qpid/collections/keyvalue/DefaultMapEntry.java | 67 -- .../java/org/apache/qpid/jms/BrokerDetails.java | 4 +- .../java/org/apache/qpid/jms/ConnectionURL.java | 1 - .../java/org/apache/qpid/jms/FailoverPolicy.java | 12 +- .../java/org/apache/qpid/jms/MessageProducer.java | 3 +- .../src/main/java/org/apache/qpid/jms/Session.java | 4 +- .../qpid/jms/failover/FailoverExchangeMethod.java | 26 +- .../jms/failover/FailoverRoundRobinServers.java | 8 +- .../qpid/jms/failover/FailoverSingleServer.java | 19 +- .../org/apache/qpid/jms/failover/NoFailover.java | 2 +- .../jndi/PropertiesFileInitialContextFactory.java | 42 +- .../java/org/apache/qpid/jndi/ReadOnlyContext.java | 19 +- .../org/apache/qpid/naming/ReadOnlyContext.java | 509 ----------- .../java/org/apache/qpid/naming/jndi.properties | 40 - .../apache/qpid/nclient/MessagePartListener.java | 3 - .../qpid/nclient/util/ByteBufferMessage.java | 17 +- .../nclient/util/MessagePartListenerAdapter.java | 11 +- .../apache/qpid/client/AMQConnectionUnitTest.java | 9 +- .../java/org/apache/qpid/client/AMQQueueTest.java | 14 +- .../apache/qpid/client/AMQSession_0_10Test.java | 75 +- .../qpid/client/BasicMessageConsumer_0_8_Test.java | 4 +- .../apache/qpid/client/DispatcherDaemonTest.java | 67 ++ .../org/apache/qpid/client/MockAMQConnection.java | 6 +- .../message/AMQMessageDelegate_0_10Test.java | 108 +++ .../client/message/AbstractJMSMessageTest.java | 4 +- .../client/protocol/AMQProtocolHandlerTest.java | 16 +- .../security/CallbackHandlerRegistryTest.java | 9 +- .../UsernameHashedPasswordCallbackHandlerTest.java | 15 +- .../UsernamePasswordCallbackHandlerTest.java | 12 +- .../ClassLoadingAwareObjectInputStreamTest.java | 8 +- .../org/apache/qpid/jms/FailoverPolicyTest.java | 16 +- .../unit/basic/FieldTableKeyEnumeratorTest.java | 11 +- .../test/unit/basic/FieldTablePropertyTest.java | 7 +- .../ChannelCloseMethodHandlerNoCloseOk.java | 6 +- .../client/channelclose/NoCloseOKStateManager.java | 31 +- .../client/destinationurl/DestinationURLTest.java | 4 +- .../test/unit/client/message/BytesMessageTest.java | 11 +- .../test/unit/client/message/MapMessageTest.java | 6 +- .../unit/client/message/ObjectMessageUnitTest.java | 6 +- .../unit/client/message/StreamMessageTest.java | 11 +- .../test/unit/client/message/TextMessageTest.java | 4 +- .../qpid/test/unit/jndi/JNDIPropertyFileTest.java | 13 +- .../test/unit/message/MessageConverterTest.java | 24 +- .../qpid/test/unit/message/NonQpidMessage.java | 5 +- .../qpid/test/unit/message/TestAMQSession.java | 26 +- qpid/java/common/Composite.tpl | 54 +- qpid/java/common/Invoker.tpl | 3 - qpid/java/common/Type.tpl | 21 +- qpid/java/common/bin/qpid-run | 2 +- qpid/java/common/build.xml | 10 +- qpid/java/common/genutil.py | 6 +- .../java/common/src/main/grammar/SelectorParser.jj | 612 +++++++++++++ qpid/java/common/src/main/java/common.bnd | 2 +- .../apache/configuration/PropertyNameResolver.java | 129 --- .../java/org/apache/qpid/AMQChannelException.java | 4 +- .../org/apache/qpid/AMQConnectionException.java | 6 +- .../apache/qpid/AMQConnectionFailureException.java | 6 +- .../java/org/apache/qpid/AMQStoreException.java | 4 +- .../apache/qpid/AMQUnresolvedAddressException.java | 2 +- .../main/java/org/apache/qpid/ConsoleOutput.java | 62 -- .../src/main/java/org/apache/qpid/QpidConfig.java | 111 --- .../main/java/org/apache/qpid/SerialException.java | 40 - .../src/main/java/org/apache/qpid/api/Message.java | 8 +- .../java/org/apache/qpid/codec/AMQDecoder.java | 24 +- .../org/apache/qpid/common/AMQPFilterTypes.java | 4 +- .../org/apache/qpid/common/ClientProperties.java | 52 -- .../apache/qpid/common/ServerPropertyNames.java | 4 + .../org/apache/qpid/configuration/Accessor.java | 19 +- .../qpid/configuration/ClientProperties.java | 54 +- .../qpid/configuration/PropertyException.java | 1 - .../apache/qpid/configuration/PropertyUtils.java | 8 +- .../apache/qpid/configuration/QpidProperty.java | 21 +- .../src/main/java/org/apache/qpid/dtx/XidImpl.java | 6 +- .../org/apache/qpid/exchange/ExchangeDefaults.java | 4 + .../apache/qpid/filter/ArithmeticExpression.java | 272 ++++++ .../org/apache/qpid/filter/BinaryExpression.java | 90 ++ .../org/apache/qpid/filter/BooleanExpression.java | 36 + .../apache/qpid/filter/ComparisonExpression.java | 596 +++++++++++++ .../org/apache/qpid/filter/ConstantExpression.java | 207 +++++ .../java/org/apache/qpid/filter/Expression.java | 34 + .../org/apache/qpid/filter/FilterableMessage.java | 41 + .../org/apache/qpid/filter/LogicExpression.java | 118 +++ .../org/apache/qpid/filter/PropertyExpression.java | 234 +++++ .../qpid/filter/SelectorParsingException.java | 36 + .../org/apache/qpid/filter/UnaryExpression.java | 340 ++++++++ .../main/java/org/apache/qpid/framing/AMQBody.java | 7 +- .../java/org/apache/qpid/framing/AMQDataBlock.java | 2 - .../apache/qpid/framing/AMQDataBlockDecoder.java | 6 +- .../java/org/apache/qpid/framing/AMQFrame.java | 2 +- .../org/apache/qpid/framing/AMQMethodBody.java | 5 - .../apache/qpid/framing/AMQMethodBodyFactory.java | 8 +- .../org/apache/qpid/framing/AMQShortString.java | 8 +- .../java/org/apache/qpid/framing/AMQTypeMap.java | 4 + .../org/apache/qpid/framing/AMQTypedValue.java | 6 +- .../qpid/framing/BasicContentHeaderProperties.java | 141 +-- .../apache/qpid/framing/ByteArrayDataInput.java | 2 - .../java/org/apache/qpid/framing/ContentBody.java | 21 +- .../apache/qpid/framing/ContentBodyFactory.java | 7 +- .../org/apache/qpid/framing/ContentHeaderBody.java | 45 +- .../qpid/framing/ContentHeaderBodyFactory.java | 7 +- .../qpid/framing/ContentHeaderProperties.java | 1 - .../framing/ContentHeaderPropertiesFactory.java | 5 +- .../org/apache/qpid/framing/EncodingUtils.java | 19 +- .../java/org/apache/qpid/framing/FieldTable.java | 6 +- .../org/apache/qpid/framing/FieldTableFactory.java | 5 +- .../org/apache/qpid/framing/HeartbeatBody.java | 6 +- .../apache/qpid/framing/ProtocolInitiation.java | 38 +- .../qpid/framing/SmallCompositeAMQDataBlock.java | 99 --- .../qpid/framing/VersionSpecificRegistry.java | 200 ----- .../abstraction/MessagePublishInfoImpl.java | 1 - .../qpid/framing/amqp_0_9/MethodConverter_0_9.java | 10 +- .../framing/amqp_0_91/MethodConverter_0_91.java | 10 +- .../qpid/framing/amqp_8_0/MethodConverter_8_0.java | 12 +- .../java/org/apache/qpid/messaging/Address.java | 4 +- .../apache/qpid/messaging/util/AddressParser.java | 8 +- .../java/org/apache/qpid/messaging/util/JAddr.java | 12 +- .../java/org/apache/qpid/messaging/util/Lexer.java | 2 - .../org/apache/qpid/messaging/util/PyPrint.java | 3 + .../pool/ReferenceCountingExecutorService.java | 2 +- .../qpid/properties/ConnectionStartProperties.java | 93 ++ .../java/org/apache/qpid/protocol/AMQConstant.java | 4 +- .../apache/qpid/protocol/AMQMethodListener.java | 2 +- .../protocol/AMQVersionAwareProtocolSession.java | 9 +- .../org/apache/qpid/protocol/ProtocolEngine.java | 6 +- .../qpid/protocol/ProtocolEngineFactory.java | 4 +- .../org/apache/qpid/ssl/SSLContextFactory.java | 34 +- .../thread/LoggingUncaughtExceptionHandler.java | 4 +- .../org/apache/qpid/thread/QpidThreadExecutor.java | 2 - .../java/org/apache/qpid/thread/Threading.java | 6 +- .../java/org/apache/qpid/transport/Binary.java | 4 +- .../org/apache/qpid/transport/ClientDelegate.java | 63 +- .../java/org/apache/qpid/transport/Connection.java | 61 +- .../apache/qpid/transport/ConnectionDelegate.java | 11 +- .../apache/qpid/transport/ConnectionSettings.java | 89 +- .../java/org/apache/qpid/transport/Header.java | 2 +- .../java/org/apache/qpid/transport/Method.java | 4 +- .../transport/NetworkTransportConfiguration.java | 4 + .../org/apache/qpid/transport/OpenException.java | 34 - .../org/apache/qpid/transport/ProtocolHeader.java | 6 +- .../main/java/org/apache/qpid/transport/Range.java | 12 +- .../java/org/apache/qpid/transport/RangeSet.java | 6 +- .../org/apache/qpid/transport/RangeSetFactory.java | 4 + .../org/apache/qpid/transport/RangeSetImpl.java | 66 +- .../org/apache/qpid/transport/ServerDelegate.java | 24 +- .../java/org/apache/qpid/transport/Session.java | 27 +- .../qpid/transport/SessionClosedException.java | 3 - .../apache/qpid/transport/SessionException.java | 2 - .../java/org/apache/qpid/transport/Struct.java | 7 +- .../qpid/transport/codec/AbstractDecoder.java | 16 +- .../qpid/transport/codec/AbstractEncoder.java | 33 +- .../org/apache/qpid/transport/codec/BBDecoder.java | 4 +- .../org/apache/qpid/transport/codec/Decoder.java | 6 +- .../org/apache/qpid/transport/codec/Encoder.java | 6 +- .../apache/qpid/transport/network/Assembler.java | 16 +- .../qpid/transport/network/ConnectionBinding.java | 4 +- .../qpid/transport/network/Disassembler.java | 4 +- .../org/apache/qpid/transport/network/Frame.java | 9 +- .../network/IncomingNetworkTransport.java | 4 +- .../qpid/transport/network/InputHandler.java | 12 +- .../qpid/transport/network/NetworkConnection.java | 4 +- .../network/OutgoingNetworkTransport.java | 9 +- .../apache/qpid/transport/network/Transport.java | 10 +- .../transport/network/io/IoNetworkConnection.java | 11 +- .../transport/network/io/IoNetworkTransport.java | 95 +- .../qpid/transport/network/io/IoReceiver.java | 3 +- .../apache/qpid/transport/network/io/IoSender.java | 16 +- .../transport/network/security/SecurityLayer.java | 16 +- .../network/security/SecurityLayerFactory.java | 13 +- .../network/security/sasl/SASLEncryptor.java | 31 +- .../network/security/sasl/SASLReceiver.java | 16 +- .../network/security/sasl/SASLSender.java | 22 +- .../security/ssl/QpidClientX509KeyManager.java | 19 +- .../network/security/ssl/SSLReceiver.java | 12 +- .../transport/network/security/ssl/SSLSender.java | 16 +- .../transport/network/security/ssl/SSLUtil.java | 20 +- .../org/apache/qpid/transport/util/Functions.java | 7 +- .../apache/qpid/transport/util/SliceIterator.java | 59 -- .../java/org/apache/qpid/url/AMQBindingURL.java | 23 +- .../java/org/apache/qpid/url/BindingURLParser.java | 13 +- .../main/java/org/apache/qpid/url/URLHelper.java | 5 +- .../java/org/apache/qpid/util/BytesDataOutput.java | 178 ++++ .../org/apache/qpid/util/CommandLineParser.java | 18 +- .../ConcurrentLinkedMessageQueueAtomicSize.java | 258 ------ .../qpid/util/ConcurrentLinkedQueueAtomicSize.java | 70 -- .../qpid/util/ConcurrentLinkedQueueNoSize.java | 38 - .../main/java/org/apache/qpid/util/FileUtils.java | 4 + .../java/org/apache/qpid/util/MessageQueue.java | 43 - .../main/java/org/apache/qpid/util/NetMatcher.java | 88 +- .../org/apache/qpid/util/PrettyPrintingUtils.java | 75 -- .../src/main/java/org/apache/qpid/util/Serial.java | 5 +- .../main/java/org/apache/qpid/util/Strings.java | 4 +- .../src/main/java/org/apache/qpid/util/UUIDs.java | 3 + .../util/concurrent/AlreadyUnblockedException.java | 34 - .../qpid/util/concurrent/BatchSynchQueue.java | 122 --- .../qpid/util/concurrent/BatchSynchQueueBase.java | 834 ------------------ .../apache/qpid/util/concurrent/BooleanLatch.java | 128 --- .../org/apache/qpid/util/concurrent/Capacity.java | 35 - .../apache/qpid/util/concurrent/SynchBuffer.java | 50 -- .../qpid/util/concurrent/SynchException.java | 52 -- .../apache/qpid/util/concurrent/SynchQueue.java | 48 -- .../apache/qpid/util/concurrent/SynchRecord.java | 74 -- .../org/apache/qpid/util/concurrent/SynchRef.java | 51 -- .../java/org/apache/qpid/AMQExceptionTest.java | 3 +- .../java/org/apache/qpid/codec/AMQDecoderTest.java | 12 +- .../codec/MockAMQVersionAwareProtocolSession.java | 4 +- .../qpid/configuration/QpidPropertyTest.java | 166 ++++ .../apache/qpid/framing/AMQShortStringTest.java | 4 +- .../framing/BasicContentHeaderPropertiesTest.java | 14 +- .../qpid/framing/PropertyFieldTableTest.java | 14 +- .../abstraction/MessagePublishInfoImplTest.java | 8 +- .../pool/ReferenceCountingExecutorServiceTest.java | 4 +- .../org/apache/qpid/ssl/SSLContextFactoryTest.java | 21 +- .../org/apache/qpid/test/utils/QpidTestCase.java | 17 +- .../qpid/transport/ConnectionSettingsTest.java | 133 ++- .../org/apache/qpid/transport/ConnectionTest.java | 26 +- .../org/apache/qpid/transport/RangeSetTest.java | 123 ++- .../qpid/transport/TestNetworkConnection.java | 15 +- .../qpid/transport/network/TransportTest.java | 7 +- .../qpid/transport/network/io/IoAcceptor.java | 2 - .../qpid/transport/network/io/IoTransport.java | 6 +- .../qpid/util/ByteBufferInputStreamTest.java | 4 +- .../apache/qpid/util/CommandLineParserTest.java | 5 +- .../org/apache/qpid/util/PropertyUtilsTest.java | 5 - .../test/java/org/apache/qpid/util/SerialTest.java | 4 - .../templates/method/version/MethodBodyClass.vm | 6 - .../templates/model/MethodDispatcherInterface.vm | 5 +- .../model/version/MethodDispatcherInterface.vm | 4 +- qpid/java/systests/build.xml | 6 +- .../systests/etc/config-systests-firewall-2.xml | 7 +- .../systests/etc/config-systests-firewall-3.xml | 7 +- .../java/systests/etc/config-systests-settings.xml | 4 +- .../qpid/client/AMQQueueDeferredOrderingTest.java | 13 +- .../apache/qpid/client/AMQTestConnection_0_10.java | 2 +- .../org/apache/qpid/client/DispatcherTest.java | 22 +- .../client/MessageListenerMultiConsumerTest.java | 9 +- .../apache/qpid/client/MessageListenerTest.java | 11 +- .../qpid/client/ResetMessageListenerTest.java | 11 +- .../org/apache/qpid/client/SessionCreateTest.java | 11 +- .../client/failover/FailoverBehaviourTest.java | 23 +- .../client/message/AMQPEncodedMapMessageTest.java | 28 +- .../qpid/client/message/NonQpidObjectMessage.java | 5 +- .../client/prefetch/PrefetchBehaviourTest.java | 55 +- .../client/redelivered/RedeliveredMessageTest.java | 3 +- .../java/org/apache/qpid/client/ssl/SSLTest.java | 13 +- .../org/apache/qpid/jms/xa/XAResourceTest.java | 18 +- .../management/jmx/ManagedBrokerMBeanTest.java | 12 +- .../management/jmx/ManagedConnectionMBeanTest.java | 55 +- .../qpid/management/jmx/ManagedQueueMBeanTest.java | 278 +++++- .../jmx/MessageConnectionStatisticsTest.java | 9 +- .../jmx/MessageStatisticsDeliveryTest.java | 11 +- .../jmx/MessageStatisticsReportingTest.java | 4 +- .../qpid/management/jmx/MessageStatisticsTest.java | 26 +- .../management/jmx/MessageStatisticsTestCase.java | 14 +- .../org/apache/qpid/scripts/QpidPasswdTest.java | 75 ++ .../org/apache/qpid/server/BrokerStartupTest.java | 13 +- .../qpid/server/SupportedProtocolVersionsTest.java | 147 ++++ .../configuration/ServerConfigurationFileTest.java | 3 +- .../ReturnUnroutableMandatoryMessageTest.java | 28 +- .../qpid/server/failover/FailoverMethodTest.java | 55 +- .../apache/qpid/server/failure/HeapExhaustion.java | 9 +- .../qpid/server/logging/AbstractTestLogging.java | 17 +- .../server/logging/AccessControlLoggingTest.java | 11 +- .../apache/qpid/server/logging/AlertingTest.java | 8 +- .../qpid/server/logging/BindingLoggingTest.java | 8 +- .../qpid/server/logging/BrokerLoggingTest.java | 6 +- .../qpid/server/logging/ConnectionLoggingTest.java | 47 +- .../logging/DerbyMessageStoreLoggingTest.java | 3 +- .../qpid/server/logging/ExchangeLoggingTest.java | 29 +- .../qpid/server/logging/ManagementLoggingTest.java | 2 +- .../logging/MemoryMessageStoreLoggingTest.java | 6 +- .../qpid/server/logging/QueueLoggingTest.java | 10 +- .../server/logging/SubscriptionLoggingTest.java | 16 +- .../server/logging/VirtualHostLoggingTest.java | 6 +- .../message/MessageProtocolConversionTest.java | 2 - .../persistent/NoLocalAfterRecoveryTest.java | 214 ++--- .../server/queue/DeepQueueConsumeWithSelector.java | 2 +- .../org/apache/qpid/server/queue/ModelTest.java | 1 - .../queue/MultipleTransactedBatchProducerTest.java | 12 +- .../qpid/server/queue/PersistentTestManual.java | 1 + .../qpid/server/queue/PriorityQueueTest.java | 15 +- .../qpid/server/queue/ProducerFlowControlTest.java | 234 ++--- .../server/queue/QueueDepthWithSelectorTest.java | 10 +- .../apache/qpid/server/queue/SortedQueueTest.java | 95 +- .../apache/qpid/server/queue/TimeToLiveTest.java | 23 +- .../server/security/acl/AbstractACLTestCase.java | 28 +- .../server/security/acl/ExhaustiveACLTest.java | 6 +- .../server/security/acl/ExternalACLJMXTest.java | 6 +- .../qpid/server/security/acl/ExternalACLTest.java | 8 +- .../security/firewall/FirewallConfigTest.java | 51 +- .../qpid/server/store/PersistentStoreTest.java | 166 ++-- .../apache/qpid/server/store/SlowMessageStore.java | 18 +- .../org/apache/qpid/server/util/AveragedRun.java | 4 +- .../org/apache/qpid/systest/GlobalTopicsTest.java | 5 - .../qpid/systest/MergeConfigurationTest.java | 17 +- .../org/apache/qpid/systest/TestingBaseCase.java | 5 +- .../org/apache/qpid/test/client/CancelTest.java | 100 --- .../org/apache/qpid/test/client/DupsOkTest.java | 4 +- .../apache/qpid/test/client/FlowControlTest.java | 11 +- .../ImmediateAndMandatoryPublishingTest.java | 290 +++++++ .../qpid/test/client/QueueBrowserAutoAckTest.java | 31 +- .../apache/qpid/test/client/RollbackOrderTest.java | 16 +- .../destination/AddressBasedDestinationTest.java | 40 +- .../qpid/test/client/failover/FailoverTest.java | 16 +- .../test/client/message/JMSDestinationTest.java | 2 +- .../qpid/test/client/message/JMSReplyToTest.java | 169 ++++ .../test/client/message/MessageToStringTest.java | 6 +- .../test/client/message/ObjectMessageTest.java | 7 +- .../qpid/test/client/message/SelectorTest.java | 24 +- .../org/apache/qpid/test/client/queue/LVQTest.java | 10 +- .../qpid/test/client/queue/QueuePolicyTest.java | 13 +- .../test/client/timeouts/SyncWaitDelayTest.java | 12 +- .../client/timeouts/SyncWaitTimeoutDelayTest.java | 2 +- .../test/framework/CauseFailureUserPrompt.java | 2 - .../org/apache/qpid/test/framework/CircuitEnd.java | 6 +- .../apache/qpid/test/framework/CircuitEndBase.java | 6 +- .../qpid/test/framework/ExceptionMonitor.java | 3 +- .../qpid/test/framework/FrameworkBaseCase.java | 6 +- .../test/framework/FrameworkClientBaseCase.java | 31 - .../test/framework/LocalAMQPCircuitFactory.java | 11 +- .../qpid/test/framework/LocalCircuitFactory.java | 12 +- .../apache/qpid/test/framework/MessageMonitor.java | 1 - .../framework/MessagingTestConfigProperties.java | 1 - .../org/apache/qpid/test/framework/TestUtils.java | 16 +- .../framework/clocksynch/UDPClockReference.java | 6 +- .../framework/clocksynch/UDPClockSynchronizer.java | 7 +- .../distributedcircuit/DistributedCircuitImpl.java | 11 +- .../DistributedPublisherImpl.java | 3 +- .../DistributedReceiverImpl.java | 3 +- .../distributedcircuit/TestClientCircuitEnd.java | 17 +- .../framework/distributedtesting/Coordinator.java | 33 +- .../DistributedTestDecorator.java | 8 +- .../distributedtesting/FanOutTestDecorator.java | 7 +- .../distributedtesting/InteropTestDecorator.java | 11 +- .../distributedtesting/OptOutTestCase.java | 2 +- .../framework/distributedtesting/TestClient.java | 25 +- .../TestClientControlledTest.java | 1 - .../test/framework/listeners/XMLTestListener.java | 9 +- .../localcircuit/LocalAMQPPublisherImpl.java | 8 +- .../framework/localcircuit/LocalCircuitImpl.java | 17 +- .../framework/localcircuit/LocalPublisherImpl.java | 10 +- .../framework/localcircuit/LocalReceiverImpl.java | 9 +- .../test/framework/sequencers/CircuitFactory.java | 3 +- .../framework/sequencers/FanOutCircuitFactory.java | 12 +- .../sequencers/InteropCircuitFactory.java | 12 +- .../apache/qpid/test/testcases/FailoverTest.java | 119 --- .../qpid/test/testcases/ImmediateMessageTest.java | 303 ------- .../qpid/test/testcases/MandatoryMessageTest.java | 321 ------- .../apache/qpid/test/testcases/RollbackTest.java | 132 --- .../apache/qpid/test/unit/ack/AcknowledgeTest.java | 20 +- .../qpid/test/unit/ack/ClientAcknowledgeTest.java | 4 +- .../org/apache/qpid/test/unit/ack/RecoverTest.java | 11 +- .../qpid/test/unit/basic/BytesMessageTest.java | 50 +- .../test/unit/basic/FieldTableMessageTest.java | 9 +- .../test/unit/basic/InvalidDestinationTest.java | 6 +- .../qpid/test/unit/basic/LargeMessageTest.java | 6 +- .../qpid/test/unit/basic/MapMessageTest.java | 6 +- .../test/unit/basic/MultipleConnectionTest.java | 13 +- .../qpid/test/unit/basic/ObjectMessageTest.java | 6 +- .../qpid/test/unit/basic/PropertyValueTest.java | 67 +- .../test/unit/basic/PubSubTwoConnectionTest.java | 10 +- .../apache/qpid/test/unit/basic/ReceiveTest.java | 6 +- .../qpid/test/unit/basic/SessionStartTest.java | 6 +- .../qpid/test/unit/basic/TextMessageTest.java | 6 +- .../qpid/test/unit/basic/close/CloseTest.java | 5 +- .../qpid/test/unit/client/AMQSessionTest.java | 8 +- .../test/unit/client/MaxDeliveryCountTest.java | 30 +- .../test/unit/client/QueueSessionFactoryTest.java | 4 +- .../test/unit/client/TopicSessionFactoryTest.java | 4 +- .../client/channelclose/ChannelCloseOkTest.java | 6 +- .../unit/client/channelclose/ChannelCloseTest.java | 18 +- .../channelclose/CloseWithBlockingReceiveTest.java | 6 +- .../BrokerClosesClientConnectionTest.java | 127 +++ .../client/connection/ConnectionCloseTest.java | 62 -- .../client/connection/ConnectionStartTest.java | 17 +- .../unit/client/connection/ConnectionTest.java | 12 +- .../client/connection/ExceptionListenerTest.java | 64 -- .../qpid/test/unit/client/forwardall/Client.java | 143 --- .../test/unit/client/forwardall/CombinedTest.java | 69 -- .../qpid/test/unit/client/forwardall/Service.java | 95 -- .../unit/client/forwardall/ServiceCreator.java | 112 --- .../test/unit/client/forwardall/SpecialQueue.java | 46 - .../unit/client/message/ObjectMessageTest.java | 24 +- .../client/protocol/AMQProtocolSessionTest.java | 12 +- .../client/temporaryqueue/TemporaryQueueTest.java | 8 +- .../qpid/test/unit/close/CloseBeforeAckTest.java | 12 +- .../close/JavaServerCloseRaceConditionTest.java | 1 - .../qpid/test/unit/close/MessageRequeueTest.java | 11 +- .../test/unit/close/TopicPublisherCloseTest.java | 8 +- .../qpid/test/unit/ct/DurableSubscriberTest.java | 31 +- .../qpid/test/unit/message/JMSPropertiesTest.java | 7 +- .../qpid/test/unit/message/StreamMessageTest.java | 14 +- .../apache/qpid/test/unit/message/UTF8Test.java | 11 +- .../test/unit/topic/DurableSubscriptionTest.java | 48 +- .../qpid/test/unit/topic/TemporaryTopicTest.java | 4 +- .../qpid/test/unit/topic/TopicPublisherTest.java | 10 +- .../qpid/test/unit/topic/TopicSessionTest.java | 12 +- .../test/unit/transacted/CommitRollbackTest.java | 17 +- .../qpid/test/unit/transacted/TransactedTest.java | 6 +- .../transacted/TransactionTimeoutTestCase.java | 42 +- .../qpid/test/unit/xa/AbstractXATestCase.java | 10 +- .../org/apache/qpid/test/unit/xa/FaultTest.java | 17 +- .../org/apache/qpid/test/unit/xa/QueueTest.java | 27 +- .../org/apache/qpid/test/unit/xa/TopicTest.java | 84 +- .../org/apache/qpid/test/utils/BrokerHolder.java | 2 + .../qpid/test/utils/ConversationFactory.java | 32 +- .../apache/qpid/test/utils/FailoverBaseCase.java | 25 +- .../qpid/test/utils/InternalBrokerHolder.java | 20 +- .../org/apache/qpid/test/utils/JMXTestUtils.java | 31 +- .../java/org/apache/qpid/test/utils/Piper.java | 130 +++ .../apache/qpid/test/utils/QpidBrokerTestCase.java | 234 ++--- .../qpid/test/utils/QpidClientConnection.java | 7 +- .../apache/qpid/test/utils/ReflectionUtils.java | 31 + .../qpid/test/utils/SpawnedBrokerHolder.java | 97 ++- .../org/apache/qpid/util/ClasspathScanner.java | 11 +- .../main/java/org/apache/qpid/util/LogMonitor.java | 2 +- .../java/org/apache/qpid/testkit/Receiver.java | 14 +- .../main/java/org/apache/qpid/tools/JNDICheck.java | 4 +- .../java/org/apache/qpid/tools/LatencyTest.java | 36 +- .../main/java/org/apache/qpid/tools/QpidBench.java | 2 +- 1058 files changed, 18008 insertions(+), 27285 deletions(-) delete mode 100644 qpid/java/broker-plugins/experimental/info/MANIFEST.MF delete mode 100644 qpid/java/broker-plugins/experimental/info/build.properties delete mode 100644 qpid/java/broker-plugins/experimental/info/build.xml delete mode 100644 qpid/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/Activator.java delete mode 100644 qpid/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/AppInfo.java delete mode 100644 qpid/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/Info.java delete mode 100644 qpid/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/InfoService.java delete mode 100644 qpid/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/InfoServiceImpl.java delete mode 100644 qpid/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/SystemInfo.java delete mode 100644 qpid/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/util/HttpPoster.java delete mode 100644 qpid/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/util/IniFileReader.java delete mode 100644 qpid/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/util/SoapClient.java delete mode 100644 qpid/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/util/XMLWriter.java delete mode 100644 qpid/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/systest/InfoPluginTest.java delete mode 100644 qpid/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/HttpPosterTest.java delete mode 100644 qpid/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/InfoServiceImplTest.java delete mode 100644 qpid/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/InfoServlet.java delete mode 100644 qpid/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/InfoTest.java delete mode 100644 qpid/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/IniFileReaderTest.java delete mode 100644 qpid/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/SoapClientTest.java delete mode 100644 qpid/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/SystemInfoTest.java delete mode 100644 qpid/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/XMLWriterTest.java delete mode 100644 qpid/java/broker/bin/create-example-ssl-stores.bat delete mode 100755 qpid/java/broker/bin/create-example-ssl-stores.sh delete mode 100644 qpid/java/broker/src/main/grammar/SelectorParser.jj delete mode 100644 qpid/java/broker/src/main/java/org/apache/qpid/configuration/Configuration.java delete mode 100644 qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/MessageRouter.java delete mode 100644 qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/headers/HeaderKey.java delete mode 100644 qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/headers/HeaderKeyDictionary.java delete mode 100644 qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/headers/HeaderMatcherResult.java delete mode 100644 qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/headers/HeadersMatcherDFAState.java delete mode 100644 qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/headers/HeadersParser.java delete mode 100644 qpid/java/broker/src/main/java/org/apache/qpid/server/filter/ArithmeticExpression.java delete mode 100644 qpid/java/broker/src/main/java/org/apache/qpid/server/filter/BinaryExpression.java delete mode 100644 qpid/java/broker/src/main/java/org/apache/qpid/server/filter/BooleanExpression.java delete mode 100644 qpid/java/broker/src/main/java/org/apache/qpid/server/filter/ComparisonExpression.java delete mode 100644 qpid/java/broker/src/main/java/org/apache/qpid/server/filter/ConstantExpression.java delete mode 100644 qpid/java/broker/src/main/java/org/apache/qpid/server/filter/Expression.java delete mode 100644 qpid/java/broker/src/main/java/org/apache/qpid/server/filter/LogicExpression.java delete mode 100644 qpid/java/broker/src/main/java/org/apache/qpid/server/filter/PropertyExpression.java delete mode 100644 qpid/java/broker/src/main/java/org/apache/qpid/server/filter/UnaryExpression.java delete mode 100644 qpid/java/broker/src/main/java/org/apache/qpid/server/filter/XPathExpression.java delete mode 100644 qpid/java/broker/src/main/java/org/apache/qpid/server/filter/XQueryExpression.java delete mode 100644 qpid/java/broker/src/main/java/org/apache/qpid/server/filter/XalanXPathEvaluator.java create mode 100644 qpid/java/broker/src/main/java/org/apache/qpid/server/output/ProtocolOutputConverterImpl.java delete mode 100644 qpid/java/broker/src/main/java/org/apache/qpid/server/output/amqp0_8/ProtocolOutputConverterImpl.java delete mode 100644 qpid/java/broker/src/main/java/org/apache/qpid/server/output/amqp0_9/ProtocolOutputConverterImpl.java delete mode 100644 qpid/java/broker/src/main/java/org/apache/qpid/server/output/amqp0_9_1/ProtocolOutputConverterImpl.java delete mode 100644 qpid/java/broker/src/main/java/org/apache/qpid/server/security/access/plugins/AllowAll.java delete mode 100644 qpid/java/broker/src/main/java/org/apache/qpid/server/security/access/plugins/DenyAll.java create mode 100644 qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/AbstractPasswordFilePrincipalDatabase.java create mode 100644 qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PasswordPrincipal.java create mode 100644 qpid/java/broker/src/main/java/org/apache/qpid/server/txn/AlreadyKnownDtxException.java create mode 100644 qpid/java/broker/src/main/java/org/apache/qpid/server/txn/DistributedTransaction.java create mode 100644 qpid/java/broker/src/main/java/org/apache/qpid/server/txn/DtxBranch.java create mode 100644 qpid/java/broker/src/main/java/org/apache/qpid/server/txn/DtxException.java create mode 100644 qpid/java/broker/src/main/java/org/apache/qpid/server/txn/DtxNotSelectedException.java create mode 100644 qpid/java/broker/src/main/java/org/apache/qpid/server/txn/DtxRegistry.java create mode 100644 qpid/java/broker/src/main/java/org/apache/qpid/server/txn/IncorrectDtxStateException.java create mode 100644 qpid/java/broker/src/main/java/org/apache/qpid/server/txn/JoinAndResumeDtxException.java create mode 100644 qpid/java/broker/src/main/java/org/apache/qpid/server/txn/NotAssociatedDtxException.java create mode 100644 qpid/java/broker/src/main/java/org/apache/qpid/server/txn/RollbackOnlyDtxException.java create mode 100644 qpid/java/broker/src/main/java/org/apache/qpid/server/txn/SuspendAndFailDtxException.java create mode 100644 qpid/java/broker/src/main/java/org/apache/qpid/server/txn/TimeoutDtxException.java create mode 100644 qpid/java/broker/src/main/java/org/apache/qpid/server/txn/UnknownDtxBranchException.java delete mode 100644 qpid/java/broker/src/main/java/org/apache/qpid/server/util/CircularBuffer.java delete mode 100644 qpid/java/broker/src/main/java/org/apache/qpid/server/util/LoggingProxy.java delete mode 100644 qpid/java/broker/src/test/java/org/apache/qpid/server/util/LoggingProxyTest.java create mode 100644 qpid/java/broker/src/test/java/org/apache/qpid/tools/security/PasswdTest.java delete mode 100644 qpid/java/client/example/src/main/java/README.txt delete mode 100644 qpid/java/client/example/src/main/java/org/apache/qpid/example/publisher/FileMessageDispatcher.java delete mode 100644 qpid/java/client/example/src/main/java/org/apache/qpid/example/publisher/FileMessageFactory.java delete mode 100644 qpid/java/client/example/src/main/java/org/apache/qpid/example/publisher/MessageFactoryException.java delete mode 100644 qpid/java/client/example/src/main/java/org/apache/qpid/example/publisher/MonitorMessageDispatcher.java delete mode 100644 qpid/java/client/example/src/main/java/org/apache/qpid/example/publisher/MonitorPublisher.java delete mode 100644 qpid/java/client/example/src/main/java/org/apache/qpid/example/publisher/MultiMessageDispatcher.java delete mode 100644 qpid/java/client/example/src/main/java/org/apache/qpid/example/publisher/Publisher.java delete mode 100644 qpid/java/client/example/src/main/java/org/apache/qpid/example/publisher/TopicPublisher.java delete mode 100644 qpid/java/client/example/src/main/java/org/apache/qpid/example/publisher/UndeliveredMessageException.java delete mode 100644 qpid/java/client/example/src/main/java/org/apache/qpid/example/pubsub/Client.java delete mode 100644 qpid/java/client/example/src/main/java/org/apache/qpid/example/pubsub/ConnectionSetup.java delete mode 100644 qpid/java/client/example/src/main/java/org/apache/qpid/example/pubsub/Publisher.java delete mode 100644 qpid/java/client/example/src/main/java/org/apache/qpid/example/pubsub/Subscriber.java delete mode 100644 qpid/java/client/example/src/main/java/org/apache/qpid/example/shared/ConnectionException.java delete mode 100644 qpid/java/client/example/src/main/java/org/apache/qpid/example/shared/ContextException.java delete mode 100644 qpid/java/client/example/src/main/java/org/apache/qpid/example/shared/FileUtils.java delete mode 100644 qpid/java/client/example/src/main/java/org/apache/qpid/example/shared/InitialContextHelper.java delete mode 100644 qpid/java/client/example/src/main/java/org/apache/qpid/example/shared/Statics.java delete mode 100644 qpid/java/client/example/src/main/java/org/apache/qpid/example/shared/example.properties delete mode 100644 qpid/java/client/example/src/main/java/org/apache/qpid/example/simple/reqresp/Client.java delete mode 100644 qpid/java/client/example/src/main/java/org/apache/qpid/example/simple/reqresp/Server.java delete mode 100644 qpid/java/client/example/src/main/java/org/apache/qpid/example/subscriber/MonitoredSubscriber.java delete mode 100644 qpid/java/client/example/src/main/java/org/apache/qpid/example/subscriber/MonitoredSubscriptionWrapper.java delete mode 100644 qpid/java/client/example/src/main/java/org/apache/qpid/example/subscriber/Subscriber.java delete mode 100644 qpid/java/client/example/src/main/java/org/apache/qpid/example/subscriber/SubscriptionWrapper.java delete mode 100755 qpid/java/client/example/src/main/java/runSample.sh delete mode 100644 qpid/java/client/src/main/grammar/SelectorParser.jj delete mode 100644 qpid/java/client/src/main/java/org/apache/qpid/client/DispatcherCallback.java delete mode 100644 qpid/java/client/src/main/java/org/apache/qpid/client/transport/AMQNoTransportForProtocolException.java delete mode 100644 qpid/java/client/src/main/java/org/apache/qpid/client/transport/AMQTransportConnectionException.java delete mode 100644 qpid/java/client/src/main/java/org/apache/qpid/client/transport/ITransportConnection.java delete mode 100644 qpid/java/client/src/main/java/org/apache/qpid/collections/KeyValue.java delete mode 100644 qpid/java/client/src/main/java/org/apache/qpid/collections/ReferenceMap.java delete mode 100644 qpid/java/client/src/main/java/org/apache/qpid/collections/keyvalue/AbstractKeyValue.java delete mode 100644 qpid/java/client/src/main/java/org/apache/qpid/collections/keyvalue/AbstractMapEntry.java delete mode 100644 qpid/java/client/src/main/java/org/apache/qpid/collections/keyvalue/DefaultMapEntry.java delete mode 100644 qpid/java/client/src/main/java/org/apache/qpid/naming/ReadOnlyContext.java delete mode 100644 qpid/java/client/src/main/java/org/apache/qpid/naming/jndi.properties create mode 100644 qpid/java/client/src/test/java/org/apache/qpid/client/DispatcherDaemonTest.java create mode 100644 qpid/java/client/src/test/java/org/apache/qpid/client/message/AMQMessageDelegate_0_10Test.java create mode 100644 qpid/java/common/src/main/grammar/SelectorParser.jj delete mode 100644 qpid/java/common/src/main/java/org/apache/configuration/PropertyNameResolver.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/ConsoleOutput.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/QpidConfig.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/SerialException.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/common/ClientProperties.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/filter/ArithmeticExpression.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/filter/BinaryExpression.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/filter/BooleanExpression.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/filter/ComparisonExpression.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/filter/ConstantExpression.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/filter/Expression.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/filter/FilterableMessage.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/filter/LogicExpression.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/filter/PropertyExpression.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/filter/SelectorParsingException.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/filter/UnaryExpression.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/framing/SmallCompositeAMQDataBlock.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/framing/VersionSpecificRegistry.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/properties/ConnectionStartProperties.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/transport/OpenException.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/transport/util/SliceIterator.java create mode 100644 qpid/java/common/src/main/java/org/apache/qpid/util/BytesDataOutput.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/util/ConcurrentLinkedMessageQueueAtomicSize.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/util/ConcurrentLinkedQueueAtomicSize.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/util/ConcurrentLinkedQueueNoSize.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/util/MessageQueue.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/util/PrettyPrintingUtils.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/AlreadyUnblockedException.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/BatchSynchQueue.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/BatchSynchQueueBase.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/BooleanLatch.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/Capacity.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchBuffer.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchException.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchQueue.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchRecord.java delete mode 100644 qpid/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchRef.java create mode 100644 qpid/java/common/src/test/java/org/apache/qpid/configuration/QpidPropertyTest.java create mode 100644 qpid/java/systests/src/main/java/org/apache/qpid/scripts/QpidPasswdTest.java create mode 100644 qpid/java/systests/src/main/java/org/apache/qpid/server/SupportedProtocolVersionsTest.java delete mode 100644 qpid/java/systests/src/main/java/org/apache/qpid/test/client/CancelTest.java create mode 100644 qpid/java/systests/src/main/java/org/apache/qpid/test/client/ImmediateAndMandatoryPublishingTest.java create mode 100644 qpid/java/systests/src/main/java/org/apache/qpid/test/client/message/JMSReplyToTest.java delete mode 100644 qpid/java/systests/src/main/java/org/apache/qpid/test/framework/FrameworkClientBaseCase.java delete mode 100644 qpid/java/systests/src/main/java/org/apache/qpid/test/testcases/FailoverTest.java delete mode 100644 qpid/java/systests/src/main/java/org/apache/qpid/test/testcases/ImmediateMessageTest.java delete mode 100644 qpid/java/systests/src/main/java/org/apache/qpid/test/testcases/MandatoryMessageTest.java delete mode 100644 qpid/java/systests/src/main/java/org/apache/qpid/test/testcases/RollbackTest.java create mode 100644 qpid/java/systests/src/main/java/org/apache/qpid/test/unit/client/connection/BrokerClosesClientConnectionTest.java delete mode 100644 qpid/java/systests/src/main/java/org/apache/qpid/test/unit/client/connection/ConnectionCloseTest.java delete mode 100644 qpid/java/systests/src/main/java/org/apache/qpid/test/unit/client/connection/ExceptionListenerTest.java delete mode 100644 qpid/java/systests/src/main/java/org/apache/qpid/test/unit/client/forwardall/Client.java delete mode 100644 qpid/java/systests/src/main/java/org/apache/qpid/test/unit/client/forwardall/CombinedTest.java delete mode 100644 qpid/java/systests/src/main/java/org/apache/qpid/test/unit/client/forwardall/Service.java delete mode 100644 qpid/java/systests/src/main/java/org/apache/qpid/test/unit/client/forwardall/ServiceCreator.java delete mode 100644 qpid/java/systests/src/main/java/org/apache/qpid/test/unit/client/forwardall/SpecialQueue.java create mode 100644 qpid/java/systests/src/main/java/org/apache/qpid/test/utils/Piper.java diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AbstractConfiguration.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AbstractConfiguration.java index a684e52ce4..f04dd38aca 100644 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AbstractConfiguration.java +++ b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AbstractConfiguration.java @@ -27,10 +27,10 @@ import org.apache.log4j.Logger; public abstract class AbstractConfiguration implements ConfigurationFile { - protected static final Logger _logger = Logger.getLogger(ConfigurationFile.class); + private static final Logger _logger = Logger.getLogger(ConfigurationFile.class); - protected File _file; - protected RuleSet _config; + private File _file; + private RuleSet _config; public AbstractConfiguration(File file) { diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/Action.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/Action.java index fdbd96e63e..b887d1e079 100644 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/Action.java +++ b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/Action.java @@ -21,8 +21,6 @@ package org.apache.qpid.server.security.access.config; import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; @@ -35,7 +33,7 @@ import org.apache.qpid.server.security.access.Operation; /** * An access control v2 rule action. * - * An action consists of an {@link Operation} on an {@link ObjectType} with certain properties, stored in a {@link Map}. + * An action consists of an {@link Operation} on an {@link ObjectType} with certain properties, stored in a {@link java.util.Map}. * The operation and object should be an allowable combination, based on the {@link ObjectType#isAllowed(Operation)} * method of the object, which is exposed as the {@link #isAllowed()} method here. The internal {@link #propertiesMatch(Map)} * and {@link #valueMatches(String, String)} methods are used to determine wildcarded matching of properties, with @@ -111,10 +109,9 @@ public class Action /** @see Comparable#compareTo(Object) */ public boolean matches(Action a) { - return (Operation.ALL == a.getOperation() - || (getOperation() == a.getOperation() - && getObjectType() == a.getObjectType() - && _properties.matches(a.getProperties()))); + return ((Operation.ALL == a.getOperation() || getOperation() == a.getOperation()) + && (ObjectType.ALL == a.getObjectType() || getObjectType() == a.getObjectType()) + && _properties.matches(a.getProperties())); } /** @@ -136,12 +133,6 @@ public class Action } else if (a.getOperation() == b.getOperation()) { - // Same operator, compare rest of action - -// || (getOperation() == a.getOperation() -// && getObjectType() == a.getObjectType() -// && _properties.matches(a.getProperties()))); - return 1; // b is more specific } else // Different operations diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/PlainConfiguration.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/PlainConfiguration.java index 9f2168a31c..b299b62538 100644 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/PlainConfiguration.java +++ b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/PlainConfiguration.java @@ -78,7 +78,7 @@ public class PlainConfiguration extends AbstractConfiguration try { - _st = new StreamTokenizer(new BufferedReader(new FileReader(_file))); + _st = new StreamTokenizer(new BufferedReader(new FileReader(getFile()))); _st.resetSyntax(); // setup the tokenizer _st.commentChar(COMMENT); // single line comments diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/RuleSet.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/RuleSet.java index 402b991419..815df99f80 100644 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/RuleSet.java +++ b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/RuleSet.java @@ -312,9 +312,9 @@ public class RuleSet return true; } - // C++ broker authorise function prototype + // CPP broker authorise function prototype // virtual bool authorise(const std::string& id, const Action& action, const ObjectType& objType, - // const std::string& name, std::map* params=0); + // const std::string& name, std::map* params=0) // Possibly add a String name paramater? diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/AccessControl.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/AccessControl.java index a97b66a287..d8a5bd4085 100644 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/AccessControl.java +++ b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/AccessControl.java @@ -109,7 +109,7 @@ public class AccessControl extends AbstractPlugin { super.configure(config); - AccessControlConfiguration accessConfig = (AccessControlConfiguration) _config; + AccessControlConfiguration accessConfig = (AccessControlConfiguration) getConfig(); _ruleSet = accessConfig.getRuleSet(); } diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/AccessControlActivator.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/AccessControlActivator.java index 72eac7dbe6..7c83446cf1 100644 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/AccessControlActivator.java +++ b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/AccessControlActivator.java @@ -23,10 +23,9 @@ package org.apache.qpid.server.security.access.plugins; import org.apache.qpid.server.configuration.plugins.ConfigurationPluginFactory; import org.apache.qpid.server.security.SecurityPluginActivator; import org.apache.qpid.server.security.SecurityPluginFactory; -import org.osgi.framework.BundleActivator; /** - * The OSGi {@link BundleActivator} for {@link AccessControl}. + * The OSGi {@link org.osgi.framework.BundleActivator} for {@link AccessControl}. */ public class AccessControlActivator extends SecurityPluginActivator { diff --git a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/AccessControlConfiguration.java b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/AccessControlConfiguration.java index b5c89910a6..c4db6db820 100644 --- a/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/AccessControlConfiguration.java +++ b/qpid/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/AccessControlConfiguration.java @@ -58,7 +58,7 @@ public class AccessControlConfiguration extends ConfigurationPlugin public String getFileName() { - return _configuration.getString(""); + return getConfig().getString(""); } public void validateConfiguration() throws ConfigurationException diff --git a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/AccessControlTest.java b/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/AccessControlTest.java index 09d26e5451..61e867f459 100644 --- a/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/AccessControlTest.java +++ b/qpid/java/broker-plugins/access-control/src/test/java/org/apache/qpid/server/security/access/plugins/AccessControlTest.java @@ -24,6 +24,7 @@ import java.util.Arrays; import junit.framework.TestCase; +import org.apache.commons.configuration.ConfigurationException; import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin; import org.apache.qpid.server.logging.UnitTestMessageLogger; import org.apache.qpid.server.logging.actors.CurrentActor; @@ -52,10 +53,20 @@ public class AccessControlTest extends TestCase private AccessControl _plugin = null; // Class under test private final UnitTestMessageLogger messageLogger = new UnitTestMessageLogger(); - protected void setUp() throws Exception + private void setUpGroupAccessControl() throws ConfigurationException { - super.setUp(); + configureAccessControl(createGroupRuleSet()); + } + + private void configureAccessControl(final RuleSet rs) throws ConfigurationException + { + _plugin = (AccessControl) AccessControl.FACTORY.newInstance(createConfiguration(rs)); + SecurityManager.setThreadSubject(null); + CurrentActor.set(new TestLogActor(messageLogger)); + } + private RuleSet createGroupRuleSet() + { final RuleSet rs = new RuleSet(); rs.addGroup("aclGroup1", Arrays.asList(new String[] {"member1", "member2"})); @@ -68,11 +79,7 @@ public class AccessControlTest extends TestCase // Catch all rule rs.grant(3, Rule.ALL, Permission.DENY_LOG, Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); - _plugin = (AccessControl) AccessControl.FACTORY.newInstance(createConfiguration(rs)); - - SecurityManager.setThreadSubject(null); - - CurrentActor.set(new TestLogActor(messageLogger)); + return rs; } protected void tearDown() throws Exception @@ -81,68 +88,238 @@ public class AccessControlTest extends TestCase SecurityManager.setThreadSubject(null); } - /** + /** * ACL plugin must always abstain if there is no subject attached to the thread. */ - public void testNoSubjectAlwaysAbstains() + public void testNoSubjectAlwaysAbstains() throws ConfigurationException { + setUpGroupAccessControl(); SecurityManager.setThreadSubject(null); final Result result = _plugin.authorise(Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); assertEquals(Result.ABSTAIN, result); } - /** + /** * Tests that an allow rule expressed with a username allows an operation performed by a thread running * with the same username. */ - public void testUsernameAllowsOperation() + public void testUsernameAllowsOperation() throws ConfigurationException { + setUpGroupAccessControl(); SecurityManager.setThreadSubject(TestPrincipalUtils.createTestSubject("user1")); final Result result = _plugin.authorise(Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); assertEquals(Result.ALLOWED, result); } - /** + /** * Tests that an allow rule expressed with an ACL groupname allows an operation performed by a thread running * by a user who belongs to the same group.. */ - public void testAclGroupMembershipAllowsOperation() + public void testAclGroupMembershipAllowsOperation() throws ConfigurationException { + setUpGroupAccessControl(); SecurityManager.setThreadSubject(TestPrincipalUtils.createTestSubject("member1")); final Result result = _plugin.authorise(Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); assertEquals(Result.ALLOWED, result); } - /** + /** * Tests that a deny rule expressed with an External groupname denies an operation performed by a thread running * by a user who belongs to the same group. */ - public void testExternalGroupMembershipDeniesOperation() + public void testExternalGroupMembershipDeniesOperation() throws ConfigurationException { + setUpGroupAccessControl(); SecurityManager.setThreadSubject(TestPrincipalUtils.createTestSubject("user3", "extGroup1")); - + final Result result = _plugin.authorise(Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); assertEquals(Result.DENIED, result); } - /** + /** * Tests that the catch all deny denies the operation and logs with the logging actor. */ - public void testCatchAllRuleDeniesUnrecognisedUsername() + public void testCatchAllRuleDeniesUnrecognisedUsername() throws ConfigurationException { + setUpGroupAccessControl(); SecurityManager.setThreadSubject(TestPrincipalUtils.createTestSubject("unknown", "unkgroup1", "unkgroup2")); - + assertEquals("Expecting zero messages before test", 0, messageLogger.getLogMessages().size()); final Result result = _plugin.authorise(Operation.ACCESS, ObjectType.VIRTUALHOST, ObjectProperties.EMPTY); assertEquals(Result.DENIED, result); - + assertEquals("Expecting one message before test", 1, messageLogger.getLogMessages().size()); assertTrue("Logged message does not contain expected string", messageLogger.messageContains(0, "ACL-1002")); } - + + /** + * Tests that a grant access method rule allows any access operation to be performed on any component + */ + public void testAuthoriseAccessMethodWhenAllAccessOperationsAllowedOnAllComponents() throws ConfigurationException + { + final RuleSet rs = new RuleSet(); + + // grant user4 access right on any method in any component + rs.grant(1, "user4", Permission.ALLOW, Operation.ACCESS, ObjectType.METHOD, new ObjectProperties(ObjectProperties.STAR)); + configureAccessControl(rs); + SecurityManager.setThreadSubject(TestPrincipalUtils.createTestSubject("user4")); + + ObjectProperties actionProperties = new ObjectProperties("getName"); + actionProperties.put(ObjectProperties.Property.COMPONENT, "Test"); + + final Result result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, actionProperties); + assertEquals(Result.ALLOWED, result); + } + + /** + * Tests that a grant access method rule allows any access operation to be performed on a specified component + */ + public void testAuthoriseAccessMethodWhenAllAccessOperationsAllowedOnSpecifiedComponent() throws ConfigurationException + { + final RuleSet rs = new RuleSet(); + + // grant user5 access right on any methods in "Test" component + ObjectProperties ruleProperties = new ObjectProperties(ObjectProperties.STAR); + ruleProperties.put(ObjectProperties.Property.COMPONENT, "Test"); + rs.grant(1, "user5", Permission.ALLOW, Operation.ACCESS, ObjectType.METHOD, ruleProperties); + configureAccessControl(rs); + SecurityManager.setThreadSubject(TestPrincipalUtils.createTestSubject("user5")); + + ObjectProperties actionProperties = new ObjectProperties("getName"); + actionProperties.put(ObjectProperties.Property.COMPONENT, "Test"); + Result result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, actionProperties); + assertEquals(Result.ALLOWED, result); + + actionProperties.put(ObjectProperties.Property.COMPONENT, "Test2"); + result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, actionProperties); + assertEquals(Result.DEFER, result); + } + + /** + * Tests that a grant access method rule allows any access operation to be performed on a specified component + */ + public void testAuthoriseAccessMethodWhenSpecifiedAccessOperationsAllowedOnSpecifiedComponent() throws ConfigurationException + { + final RuleSet rs = new RuleSet(); + + // grant user6 access right on "getAttribute" method in "Test" component + ObjectProperties ruleProperties = new ObjectProperties("getAttribute"); + ruleProperties.put(ObjectProperties.Property.COMPONENT, "Test"); + rs.grant(1, "user6", Permission.ALLOW, Operation.ACCESS, ObjectType.METHOD, ruleProperties); + configureAccessControl(rs); + SecurityManager.setThreadSubject(TestPrincipalUtils.createTestSubject("user6")); + + ObjectProperties properties = new ObjectProperties("getAttribute"); + properties.put(ObjectProperties.Property.COMPONENT, "Test"); + Result result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, properties); + assertEquals(Result.ALLOWED, result); + + properties.put(ObjectProperties.Property.COMPONENT, "Test2"); + result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, properties); + assertEquals(Result.DEFER, result); + + properties = new ObjectProperties("getAttribute2"); + properties.put(ObjectProperties.Property.COMPONENT, "Test"); + result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, properties); + assertEquals(Result.DEFER, result); + } + + /** + * Tests that granting of all method rights on a method allows a specified operation to be performed on any component + */ + public void testAuthoriseAccessUpdateMethodWhenAllRightsGrantedOnSpecifiedMethodForAllComponents() throws ConfigurationException + { + final RuleSet rs = new RuleSet(); + + // grant user8 all rights on method queryNames in all component + rs.grant(1, "user8", Permission.ALLOW, Operation.ALL, ObjectType.METHOD, new ObjectProperties("queryNames")); + configureAccessControl(rs); + SecurityManager.setThreadSubject(TestPrincipalUtils.createTestSubject("user8")); + + ObjectProperties properties = new ObjectProperties(); + properties.put(ObjectProperties.Property.COMPONENT, "Test"); + properties.put(ObjectProperties.Property.NAME, "queryNames"); + + Result result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, properties); + assertEquals(Result.ALLOWED, result); + + result = _plugin.authorise(Operation.UPDATE, ObjectType.METHOD, properties); + assertEquals(Result.ALLOWED, result); + + properties = new ObjectProperties("getAttribute"); + properties.put(ObjectProperties.Property.COMPONENT, "Test"); + result = _plugin.authorise(Operation.UPDATE, ObjectType.METHOD, properties); + assertEquals(Result.DEFER, result); + + result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, properties); + assertEquals(Result.DEFER, result); + } + + /** + * Tests that granting of all method rights allows any operation to be performed on any component + */ + public void testAuthoriseAccessUpdateMethodWhenAllRightsGrantedOnAllMethodsInAllComponents() throws ConfigurationException + { + final RuleSet rs = new RuleSet(); + + // grant user9 all rights on any method in all component + rs.grant(1, "user9", Permission.ALLOW, Operation.ALL, ObjectType.METHOD, new ObjectProperties()); + configureAccessControl(rs); + SecurityManager.setThreadSubject(TestPrincipalUtils.createTestSubject("user9")); + + ObjectProperties properties = new ObjectProperties("queryNames"); + properties.put(ObjectProperties.Property.COMPONENT, "Test"); + + Result result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, properties); + assertEquals(Result.ALLOWED, result); + + result = _plugin.authorise(Operation.UPDATE, ObjectType.METHOD, properties); + assertEquals(Result.ALLOWED, result); + + properties = new ObjectProperties("getAttribute"); + properties.put(ObjectProperties.Property.COMPONENT, "Test"); + result = _plugin.authorise(Operation.UPDATE, ObjectType.METHOD, properties); + assertEquals(Result.ALLOWED, result); + + result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, properties); + assertEquals(Result.ALLOWED, result); + } + + /** + * Tests that granting of access method rights with mask allows matching operations to be performed on the specified component + */ + public void testAuthoriseAccessMethodWhenMatchingAcessOperationsAllowedOnSpecifiedComponent() throws ConfigurationException + { + final RuleSet rs = new RuleSet(); + + // grant user9 all rights on "getAttribute*" methods in Test component + ObjectProperties ruleProperties = new ObjectProperties(); + ruleProperties.put(ObjectProperties.Property.COMPONENT, "Test"); + ruleProperties.put(ObjectProperties.Property.NAME, "getAttribute*"); + + rs.grant(1, "user9", Permission.ALLOW, Operation.ACCESS, ObjectType.METHOD, ruleProperties); + configureAccessControl(rs); + SecurityManager.setThreadSubject(TestPrincipalUtils.createTestSubject("user9")); + + ObjectProperties properties = new ObjectProperties("getAttributes"); + properties.put(ObjectProperties.Property.COMPONENT, "Test"); + Result result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, properties); + assertEquals(Result.ALLOWED, result); + + properties = new ObjectProperties("getAttribute"); + properties.put(ObjectProperties.Property.COMPONENT, "Test"); + result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, properties); + assertEquals(Result.ALLOWED, result); + + properties = new ObjectProperties("getAttribut"); + properties.put(ObjectProperties.Property.COMPONENT, "Test"); + result = _plugin.authorise(Operation.ACCESS, ObjectType.METHOD, properties); + assertEquals(Result.DEFER, result); + } + /** * Creates a configuration plugin for the {@link AccessControl} plugin. */ @@ -150,6 +327,7 @@ public class AccessControlTest extends TestCase { final ConfigurationPlugin cp = new ConfigurationPlugin() { + @SuppressWarnings("unchecked") public AccessControlConfiguration getConfiguration(final String plugin) { return new AccessControlConfiguration() diff --git a/qpid/java/broker-plugins/experimental/info/MANIFEST.MF b/qpid/java/broker-plugins/experimental/info/MANIFEST.MF deleted file mode 100644 index f213104d8d..0000000000 --- a/qpid/java/broker-plugins/experimental/info/MANIFEST.MF +++ /dev/null @@ -1,16 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: QpidPlugin -Bundle-SymbolicName: qpid_info_plugin;singleton:=true -Bundle-License: http://www.apache.org/licenses/LICENSE-2.0.txt -Bundle-Version: 1.0.0 -Bundle-Activator: org.apache.qpid.info.Activator -Import-Package: org.apache.qpid.server.configuration, - org.osgi.framework, - org.apache.qpid.common, - org.apache.qpid.server.registry -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Bundle-ClassPath: . -Bundle-ActivationPolicy: lazy -Export-Package: org.apache.qpid.info;uses:="org.osgi.framework" - diff --git a/qpid/java/broker-plugins/experimental/info/build.properties b/qpid/java/broker-plugins/experimental/info/build.properties deleted file mode 100644 index bdbbe1c2af..0000000000 --- a/qpid/java/broker-plugins/experimental/info/build.properties +++ /dev/null @@ -1,31 +0,0 @@ -# -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - .,\ - plugin.xml,\ - lib/eventTrackerClient-2.7.0.jar,\ - lib/commons-logging-1.0.4.jar -src.includes = src/,\ - plugin.xml,\ - lib/,\ - build.properties,\ - bin/,\ - META-INF/ diff --git a/qpid/java/broker-plugins/experimental/info/build.xml b/qpid/java/broker-plugins/experimental/info/build.xml deleted file mode 100644 index 8f91adc5ff..0000000000 --- a/qpid/java/broker-plugins/experimental/info/build.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/qpid/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/Activator.java b/qpid/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/Activator.java deleted file mode 100644 index 21e7be26c1..0000000000 --- a/qpid/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/Activator.java +++ /dev/null @@ -1,211 +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.info; - -import org.apache.qpid.info.util.HttpPoster; -import org.apache.qpid.info.util.IniFileReader; -import org.apache.qpid.info.util.SoapClient; -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; - -import java.io.File; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -/** The Activator class for the OSGI info service */ -public class Activator implements BundleActivator -{ - - private final List _soapPropList = Arrays.asList("soap.hostname", - "soap.port", "soap.path", "soap.action", "soap.envelope"); - - private final List _httpPropList = Arrays.asList("http.url", - "http.envelope"); - - InfoServiceImpl _service = null; - - BundleContext _ctx = null; - - /** - * Start bundle method - * - * @param ctx the bundle context - */ - public void start(BundleContext ctx) throws Exception - { - if (null != ctx) - { - _ctx = ctx; - _service = new InfoServiceImpl(); - ctx.registerService(InfoService.class.getName(), _service, null); - - new Thread(new Runnable() - { - public void run() - { - sendInfo("STARTUP"); - } - }).start(); - } - } - - /** - * Stop the bundle method - * - * @param ctx the bundle context - */ - public void stop(BundleContext ctx) throws Exception - { - sendInfo("SHUTDOWN"); - } - - /** - * Sends the information message - * - * @param action label that identifies if we are starting up or shutting down - */ - private void sendInfo(String action) - { - if ((null == _ctx) && (null == _service)) - { - // invalid state - return; - } - - IniFileReader ifr = new IniFileReader(); - try - { - String QPID_HOME = System.getProperty("QPID_HOME"); - String cfgFilePath = QPID_HOME + File.separator + "etc" - + File.separator + "qpidinfo.ini"; - ifr.load(cfgFilePath); - } - catch (Throwable ex) - { - // drop everything to be silent - return; - } - - // Only send Messages if we have some sections. - if (ifr.getSections().size() != 0) - { - Info> info = _service.invoke(action); - String protocol = ifr.getSections().get("").getProperty("protocol"); - sendMessages(protocol, ifr, info); - } - } - - /** - * Sends all the messages configured in the properties file - * - * @param protocol indicates what protocol to be used: http and soap implemented - * for now - * @param ifr an instance of IniFileReader class - * @param info an instance of an Info object, encapsulating the information - * we want to send - */ - private void sendMessages(String protocol, IniFileReader ifr, - Info> info) - { - if (null != protocol) - { - // Set the global properties first (as they are the defaults) - Properties defaultProps = ifr.getSections().get(""); - if (protocol.toLowerCase().startsWith("http")) - { - for (String section : ifr.getSections().keySet()) - { - // Skip the defaults - if (section.equals("")) - { - continue; - } - Properties props = new Properties(); - props.putAll(defaultProps); - props.putAll(ifr.getSections().get(section)); - if (isValid(protocol, props)) - { - new HttpPoster(props, info.toXML()).run(); - } - } - - } - else if (protocol.toLowerCase().startsWith("soap")) - { - for (String section : ifr.getSections().keySet()) - { - Properties props = new Properties(); - props.putAll(defaultProps); - props.putAll(ifr.getSections().get(section)); - if (isValid(protocol, props)) - { - new SoapClient(info.toMap(), props).sendSOAPMessage(); - } - } - } - } - } - - /** - * Checks if the properties for a specified protocol are valid - * - * @param protocol String representing the protocol - * @param props The properties associate with the specified protocol - * @return boolean - */ - private boolean isValid(String protocol, Properties props) - { - if (null == protocol) - { - return false; - } - String value = ""; - if (protocol.toLowerCase().startsWith("http")) - { - for (String prop : _httpPropList) - { - if (null == props.get(prop)) - { - return false; - } - } - return true; - } - - if (protocol.toLowerCase().startsWith("soap")) - { - for (String prop : _soapPropList) - { - value = props.getProperty(prop); - if (null == value) - { - return false; - } - } - return true; - } - return false; - } -} // end class - diff --git a/qpid/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/AppInfo.java b/qpid/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/AppInfo.java deleted file mode 100644 index c8e9805cd9..0000000000 --- a/qpid/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/AppInfo.java +++ /dev/null @@ -1,92 +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.info; - -import org.apache.qpid.common.QpidProperties; -import org.apache.qpid.server.configuration.ServerConfiguration; -import org.apache.qpid.server.registry.ApplicationRegistry; - -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Properties; -import java.util.TreeMap; - -/** AppInfo class is gathering application specific information */ -public class AppInfo -{ - - private static final List appProps = Arrays.asList("QPID_HOME", - "QPID_WORK"); - - private static Map appInfoMap = new TreeMap(); - - /** - * getInfo method retrieves a key-value map for specific application properties - * - * @return Map - */ - public static Map getInfo() - { - - // Gather the selected app props - Properties sysprops = System.getProperties(); - String propName; - for (Iterator> it = sysprops.entrySet() - .iterator(); it.hasNext();) - { - Entry en = it.next(); - propName = en.getKey().toString(); - if (appProps.indexOf(propName) >= 0) - { - appInfoMap.put(propName, en.getValue().toString()); - } - } - - ServerConfiguration sc; - try - { - sc = ApplicationRegistry.getInstance().getConfiguration(); - if (null != sc) - { - appInfoMap.put("jmxport", sc.getJMXPortRegistryServer() + ""); - appInfoMap.put("port", sc.getPorts().toString()); - appInfoMap.put("version", QpidProperties.getReleaseVersion()); - appInfoMap.put("vhosts", "standalone"); - appInfoMap.put("KeystorePath", sc.getConnectorKeyStorePath()); - appInfoMap.put("PluginDirectory", sc.getPluginDirectory()); - appInfoMap.put("CertType", sc.getConnectorCertType()); - appInfoMap.put("QpidWork", sc.getQpidWork()); - appInfoMap.put("Bind", sc.getBind()); - } - } - catch (Exception e) - { - // drop everything to be silent - } - return appInfoMap; - - } - -} diff --git a/qpid/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/Info.java b/qpid/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/Info.java deleted file mode 100644 index 2fb9382526..0000000000 --- a/qpid/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/Info.java +++ /dev/null @@ -1,143 +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. - * - */ - -/** - * - * @author sorin - * - * Info object - */ - -package org.apache.qpid.info; - -import org.apache.qpid.info.util.XMLWriter; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Properties; - -/** - * The Info class encapsulates all the information we are collecting - * and it is able to render it in different data representations - */ -public class Info> -{ - private T _info; - - /** - * Constructor. - * - * @param info instantiates the object with a Map - */ - public Info(T info) - { - _info = info; - } - - @Override - public String toString() - { - String result = ""; - for (Iterator it = _info.keySet().iterator(); it.hasNext();) - { - String str = it.next(); - result += str + "=" + _info.get(str).toString() + "\n"; - } - return result; - } - - /** - * Renders Info map to a property object - * - * @return A Properties object representing the Info map - */ - public Properties toProps() - { - Properties props = new Properties(); - if (null == _info) - { - return null; - } - for (Iterator it = _info.keySet().iterator(); it.hasNext();) - { - String key = it.next(); - props.put(key, _info.get(key)); - } - return props; - } - - /** - * Renders Info map to a StringBuffer - * - * @return A StringBuffer object representing the Info map - */ - public StringBuffer toStringBuffer() - { - StringBuffer sb = new StringBuffer(); - for (Iterator it = _info.keySet().iterator(); it.hasNext();) - { - String str = it.next(); - sb.append(str + "=" + _info.get(str).toString() + "\n"); - } - return sb; - } - - /** - * Renders Info map to a StringBuffer containing an XML string - * - * @return A StringBuffer object containing an XML representation of the Info map - */ - public StringBuffer toXML() - { - XMLWriter xw = new XMLWriter(new StringBuffer()); - xw.writeXMLHeader(); - Map attr = new HashMap(); - xw.writeOpenTag("qpidinfo", attr); - String key; - for (Iterator it = _info.keySet().iterator(); it.hasNext();) - { - attr.clear(); - key = it.next(); - xw.writeTag(key, attr, _info.get(key).toString()); - } - xw.writeCloseTag("qpidinfo"); - return xw.getXML(); - } - - /** - * Renders Info map to a HashMap - * - * @return A HashMap object representing the Info map - */ - public HashMap toMap() - { - String key; - HashMap infoMap = new HashMap(); - for (Iterator it = _info.keySet().iterator(); it.hasNext();) - { - key = it.next(); - infoMap.put(key, _info.get(key).toString()); - } - return infoMap; - } - -} diff --git a/qpid/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/InfoService.java b/qpid/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/InfoService.java deleted file mode 100644 index 2804dfb1b4..0000000000 --- a/qpid/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/InfoService.java +++ /dev/null @@ -1,30 +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. - * - */ - - /** - * Interface exposing the service methods - */ - package org.apache.qpid.info; - - public interface InfoService - { - public Info invoke(String action); - } diff --git a/qpid/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/InfoServiceImpl.java b/qpid/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/InfoServiceImpl.java deleted file mode 100644 index 5522f2701e..0000000000 --- a/qpid/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/InfoServiceImpl.java +++ /dev/null @@ -1,66 +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. - * - */ - -/** - * - * @author sorin - * - * Implementation for Info service - */ - -package org.apache.qpid.info; - -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Map; -import java.util.SortedMap; -import java.util.TreeMap; - - -public class InfoServiceImpl implements InfoService -{ - - SortedMap infoMap = new TreeMap(); - - /** - * invoke method collects all the information from System and Application - * and encapsulates them in an Info object - * @return An instance of an Info object - */ - public Info> invoke(String action) - { - // Record the action (STARTUP/SHUTDOWN) - infoMap.put("action",action); - - // Record the current time stamp - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ"); - infoMap.put("time", sdf.format(Calendar.getInstance().getTime())); - - // Add the system specific properties - infoMap.putAll(SystemInfo.getInfo()); - - // Add the application specific properties - infoMap.putAll(AppInfo.getInfo()); - - return new Info>(infoMap); - } - -} diff --git a/qpid/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/SystemInfo.java b/qpid/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/SystemInfo.java deleted file mode 100644 index 8bd94fe14d..0000000000 --- a/qpid/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/SystemInfo.java +++ /dev/null @@ -1,91 +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.info; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.TreeMap; -import java.util.Map.Entry; - -/** - * Collector for system specific information - */ -public class SystemInfo -{ - - private static Map sysInfoMap = new TreeMap(); - - private static final List sysProps = Arrays.asList( - "java.class.path", "java.home", "java.vm.name", "java.vm.vendor", - "java.vm.version", "java.class.version", "java.runtime.version", - "os.arch", "os.name", "os.version", "sun.arch.data.model", - "user.home", "user.dir", "user.name", "user.timezone"); - - /** - * getInfo collects all the properties specified in sysprops list - * @return A Map - */ - public static Map getInfo() - { - - // Get the hostname - try - { - InetAddress addr = InetAddress.getLocalHost(); - String hostname = addr.getHostName(); - sysInfoMap.put("hostname", hostname); - sysInfoMap.put("ip", addr.getHostAddress()); - } - catch (UnknownHostException e) - { - // drop everything to be silent - } - // Get the runtime info - sysInfoMap.put("CPUCores", Runtime.getRuntime().availableProcessors() - + ""); - sysInfoMap.put("Maximum_Memory", Runtime.getRuntime().maxMemory() + ""); - sysInfoMap.put("Free_Memory", Runtime.getRuntime().freeMemory() + ""); - - // Gather the selected system props - Properties sysprops = System.getProperties(); - String propName; - for (Iterator> it = sysprops.entrySet() - .iterator(); it.hasNext();) - { - Entry en = it.next(); - propName = en.getKey().toString(); - if (sysProps.indexOf(propName) >= 0) - { - sysInfoMap.put(propName, en.getValue().toString()); - } - } - - return sysInfoMap; - - } - -} diff --git a/qpid/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/util/HttpPoster.java b/qpid/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/util/HttpPoster.java deleted file mode 100644 index d27980be05..0000000000 --- a/qpid/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/util/HttpPoster.java +++ /dev/null @@ -1,130 +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.info.util; - -import java.util.ArrayList; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.List; -import java.util.Properties; -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.net.InetAddress; -import java.net.URL; -import java.net.URLConnection; -import java.net.UnknownHostException; - -/** - * - * An simple Http post class for qpid info service - */ -public class HttpPoster implements Runnable -{ - private final String _url; - - private final Hashtable _header; - - private final List _response = new ArrayList(); - - private final StringBuffer _buf; - - /** - * Constructor - * - * @param props Properties containing the URL - * @param buf Buffer containing the message to be posted - */ - public HttpPoster(Properties props, StringBuffer buf) - { - _buf = buf; - if (null != props) - { - _url = props.getProperty("http.url"); - _header = new Hashtable(); - try - { - String hostname = InetAddress.getLocalHost().getHostName(); - _header.put("hostname", hostname); - } - catch (UnknownHostException e) - { - // Silently ignoring the error ;) - } - } - else - { - _url = null; - _header = null; - } - } - - /** Posts the message from the _buf StringBuffer to the http server */ - public void run() - { - if (null == _url) - { - return; - } - String line; - URL urlDest; - URLConnection urlConn; - try - { - urlDest = new URL(_url); - urlConn = urlDest.openConnection(); - urlConn.setDoOutput(true); - urlConn.setUseCaches(false); - for (Iterator it = _header.keySet().iterator(); it.hasNext();) - { - String prop = it.next(); - urlConn.setRequestProperty(prop, _header.get(prop)); - } - OutputStreamWriter wr = - new OutputStreamWriter(urlConn.getOutputStream()); - wr.write(_buf.toString()); - wr.flush(); - // Get the response - BufferedReader rd = new BufferedReader(new InputStreamReader( - urlConn.getInputStream())); - while ((line = rd.readLine()) != null) - { - _response.add(line); - } - } - catch (Exception ex) - { - // Silently ignoring the error ;) - } - } - - /** - * Retrieves the response from the http server - * - * @return List response received from the http server - */ - public List get_response() - { - return _response; - } - -} diff --git a/qpid/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/util/IniFileReader.java b/qpid/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/util/IniFileReader.java deleted file mode 100644 index 60a025d322..0000000000 --- a/qpid/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/util/IniFileReader.java +++ /dev/null @@ -1,193 +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.info.util; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - -/** - * This class is simple implementation of an ini file reader. It expects a - * file with the following structure: - * - * ; global values, can be overwritten in sections - * key1=value1 - * key2=value2 - * - * [Section1] - * key1=value1_new ; overwriting the global key1 - * key3=value3 - * key4=value4 - * - * [Section2] - * key5=value5 - * key6=value6 - * key7=value7 - * - * Note: Commentaries are preceded by ; or # and are supported throughout - * A commentary line at the end of section is interpreted as - * a section end marker - * - * A structure (section name, associated properties) - * is generated as a result of processing the ini file. - */ -public class IniFileReader -{ - private final Map _sections; - - private final String COMMENT_SEMICOLON = ";"; - - private final String COMMENT_HASH = "#"; - - enum State - { - IN_SECTION, OFF_SECTION, GLOBAL - } - - /* - * IniFileReader constructor - */ - - public IniFileReader() - { - _sections = new HashMap(); - } - - /** - * Cleans up the after comments or the empty spaces/tabs surrounding the given string - * - * @param str The String to be cleaned - * - * @return String Cleanup Version - */ - private String cleanUp(String str) - { - if (str.contains(COMMENT_SEMICOLON)) - { - str = str.substring(0, str.indexOf(COMMENT_SEMICOLON)); - } - if (str.contains(COMMENT_HASH)) - { - str = str.substring(0, str.indexOf(COMMENT_HASH)); - } - return str.trim(); - } - - /** - * Loads and parses the ini file with the full path specified in the argument - * - * @param fileName Full path to the ini file - * - * @throws IllegalArgumentException If the file cannot be processed - */ - public void load(String fileName) throws IllegalArgumentException - { - if (!new File(fileName).isFile()) - { - throw new IllegalArgumentException("File: " + fileName + " does not exist or cannot be read."); - } - State state = State.GLOBAL; - String line; - Properties sectionProps = new Properties(); - String sectionName = ""; - try - { - BufferedReader in = new BufferedReader(new FileReader(fileName)); - while ((line = in.readLine()) != null) - { - String str = cleanUp(line); - - // Did we get a section header? - if (str.startsWith("[")) - { - if (!str.endsWith("]")) - { - // Index of 1 to skip '[' - throw new IllegalArgumentException(str.substring(1) - + " is not closed"); - } - - // We encountered a new section header - if (state != State.IN_SECTION) - { - _sections.put(sectionName, sectionProps); - sectionProps = new Properties(); - sectionName = str.replace("[", "").replace("]", "") - .trim(); - state = State.IN_SECTION; - } - } - - // Any other line tested separately, ignore if out of a section - // and add if in section - if (str.length() == 0) - { - // We encountered a commented or an empty line, both cases - // mean we are off the section - if (state == State.IN_SECTION) - { - _sections.put(sectionName, sectionProps); - state = State.OFF_SECTION; - } - } - else - { - // proper line, add it to the props - if (state != State.OFF_SECTION) - { - if (str.contains("=")) - { - int ix = str.indexOf("="); - sectionProps.put(str.substring(0, ix).trim(), str - .substring(ix + 1).trim()); - } - } - } - } - in.close(); - } - catch (IOException e) - { - _sections.clear(); - return; - } - if (state != State.OFF_SECTION) - { - _sections.put(sectionName, sectionProps); - } - } - - /** - * Getter for the Sections Map - * - * @return Map The parsed content of the ini file in this structure - */ - public Map getSections() - { - return _sections; - } - -} diff --git a/qpid/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/util/SoapClient.java b/qpid/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/util/SoapClient.java deleted file mode 100644 index 0f66085fc3..0000000000 --- a/qpid/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/util/SoapClient.java +++ /dev/null @@ -1,155 +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. - * - */ -/** - * - * @author sorin - * - * An simple SOAP client for qpid info service - */ -package org.apache.qpid.info.util; - -import java.io.BufferedWriter; -import java.io.OutputStreamWriter; -import java.net.InetAddress; -import java.net.Socket; -import java.util.HashMap; -import java.util.Properties; - -public class SoapClient -{ - - private final StringBuffer _xmlData; - - private final Properties _destprops; - - private final String _hostname; - - private final int _port; - - private final String _urlpath; - - private final String _soapenvelope; - - private final String _soapaction; - - private final StringBuffer _soapMessage = new StringBuffer(); - - - public SoapClient(HashMap map, Properties destprops) - { - _destprops = destprops; - _hostname = (String) _destprops.get("soap.hostname"); - _port = Integer.parseInt((String) _destprops.get("soap.port")); - _urlpath = (String) destprops.get("soap.path"); - _soapenvelope = (String) destprops.get("soap.envelope"); - _soapaction = (String) destprops.get("soap.action"); - _xmlData = new StringBuffer(_soapenvelope); - replaceVariables(map); - } - - public StringBuffer getXMLData() - { - return _xmlData; - } - - public StringBuffer getSoapMessage() { - return _soapMessage; - } - - public String getSoapEnvelope() { - return _soapenvelope; - } - - /** - * Clears and sets new XML data - * @param sb the new data to set - */ - public void setXMLData(StringBuffer sb) - { - _xmlData.delete(0, _xmlData.length()); - _xmlData.append(sb); - } - - - public void replaceVariables(HashMap vars) - { - int ix = 0; - for (String var : vars.keySet()) - { - while ((ix = _xmlData.indexOf("@" + var.toUpperCase())) >= 0) - { - _xmlData.replace(ix, ix + 1 + var.length(), vars.get(var)); - } - } - } - - public void replaceVariables(Properties varProps) - { - if (varProps == null) - { - return; - } - int ix = 0; - for (Object var : varProps.keySet()) - { - while ((ix = _xmlData.indexOf("@" + var)) >= 0) - { - _xmlData.replace(ix, ix + 1 + var.toString().length(), varProps - .get(var).toString()); - } - } - } - - - public void sendSOAPMessage() - { - - try - { - InetAddress addr = InetAddress.getByName(_hostname); - Socket sock = new Socket(addr, _port); - StringBuffer sb = new StringBuffer(); - sb.append("POST " + _urlpath + " HTTP/1.1\r\n"); - sb.append("Host: " + _hostname + ":" + _port + "\r\n"); - sb.append("Content-Length: " + _xmlData.length() + "\r\n"); - sb.append("Content-Type: text/xml; charset=\"utf-8\"\r\n"); - sb.append("SOAPAction: \"urn:"+ _soapaction +"\"\r\n"); - sb.append("User-Agent: Axis2\r\n"); - sb.append("\r\n"); - // Send header - BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(sock - .getOutputStream(), "UTF-8")); - synchronized(_soapMessage) { - _soapMessage.setLength(0); - _soapMessage.append(sb); - _soapMessage.append(_xmlData); - } - // Send data - wr.write(_soapMessage.toString()); - wr.flush(); - wr.close(); - - } catch (Exception ex) - { - // Drop any exception - } - } -} diff --git a/qpid/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/util/XMLWriter.java b/qpid/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/util/XMLWriter.java deleted file mode 100644 index a266edae00..0000000000 --- a/qpid/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/util/XMLWriter.java +++ /dev/null @@ -1,100 +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.info.util; - -import java.util.Map; - -/** - * - * Naive and rudimentary XML writer - * It has methods to write the header, a tag with attributes - * and values. It escapes the XML special characters - */ -public class XMLWriter -{ - - private final StringBuffer _sb; - - private final String INDENT = " "; - - public XMLWriter(StringBuffer sb) - { - _sb = sb; - } - - public StringBuffer getXML() - { - return _sb; - } - - public void writeXMLHeader() - { - _sb.append("\n"); - } - - public void writeTag(String tagName, Map attributes, - String value) - { - writeOpenTag(tagName, attributes); - writeValue(value); - writeCloseTag(tagName); - } - - public void writeOpenTag(String tagName, Map attributes) - { - _sb.append("<").append(tagName); - if (null == attributes) - { - _sb.append(">\n"); - return; - } - for (String key : attributes.keySet()) - { - _sb.append(" ").append(key + "=\"" + attributes.get(key) + "\""); - } - _sb.append(">\n"); - - } - - private void writeValue(String val) - { - _sb.append(INDENT).append(escapeXML(val) + "\n"); - } - - public void writeCloseTag(String tagName) - { - _sb.append("\n"); - } - - private String escapeXML(String xmlStr) - { - if (null == xmlStr) - return null; - xmlStr = xmlStr.replaceAll("&", "&"); - xmlStr = xmlStr.replace("<", "<"); - xmlStr = xmlStr.replace(">", ">"); - xmlStr = xmlStr.replace("\"", """); - xmlStr = xmlStr.replace("'", "'"); - return xmlStr; - } - -} diff --git a/qpid/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/systest/InfoPluginTest.java b/qpid/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/systest/InfoPluginTest.java deleted file mode 100644 index 348e860d5f..0000000000 --- a/qpid/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/systest/InfoPluginTest.java +++ /dev/null @@ -1,277 +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.info.systest; - -import org.apache.qpid.test.utils.QpidBrokerTestCase; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.ServerSocket; -import java.net.Socket; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -public class InfoPluginTest extends QpidBrokerTestCase -{ - private String QPID_HOME = null; - - private ServerSocket _server = null; - - private int _port; - - private static final String CR = System.getProperty("line.separator"); - - private static final String FS = File.separator; - - private final String _cfgRelPath = "etc" + FS + "qpidinfo.ini"; - - private File _tmpCfgFile; - - private final String _soapEnvelopeHead = ""; - - private final String _soapEnvelopeTail = ""; - - private String _soapMessage1 = "@ACTION" + "-" + "@VERSION"; - - private String _soapMessage2 = "@VERSION" + "-" + "@ACTION"; - - private CountDownLatch _latch = new CountDownLatch(2); - - final List> _recv = new ArrayList>(); - - Thread _socketAcceptor; - - public void setUp() throws Exception - { - QPID_HOME = System.getProperty("QPID_HOME"); - if (QPID_HOME != null) - { - System.out.println("QPID_HOME=" + QPID_HOME); - } - else - { - fail("QPID_HOME not set"); - } - - startSoapServer(); - // Must start the server first to identify a free port. - createConfigFile(); - } - - public void tearDown() throws Exception - { - System.out.println("*** Stopping socket server..."); - _socketAcceptor.join(2000); - - System.out.println("*** Deleting the config file..."); - if (_tmpCfgFile.isFile()) - { - _tmpCfgFile.delete(); - } - super.tearDown(); - } - - private void createConfigFile() - { - try - { - _tmpCfgFile = new File(QPID_HOME + FS + _cfgRelPath); - _tmpCfgFile.deleteOnExit(); - if (_tmpCfgFile.isFile()) - { - _tmpCfgFile.delete(); - } - assertTrue("Unable to create file.", _tmpCfgFile.createNewFile()); - assertTrue(_tmpCfgFile.isFile()); - FileWriter fwriter = new FileWriter(_tmpCfgFile); - BufferedWriter writer = new BufferedWriter(fwriter); - writer.write("protocol=soap"); - writer.write(CR); - writer.write("soap.hostname=localhost"); - writer.write(CR); - writer.write("soap.port=" + _port); - writer.write(CR); - writer.write(CR); - writer.write("[MSG1]"); - writer.write(CR); - writer.write("soap.path=/info1"); - writer.write(CR); - writer.write("soap.action=submitinfo1"); - writer.write(CR); - writer.write("soap.envelope=" + _soapEnvelopeHead + _soapMessage1 - + _soapEnvelopeTail); - writer.write(CR); - writer.write(CR); - writer.write("[MSG2]"); - writer.write(CR); - writer.write("soap.path=/info2"); - writer.write(CR); - writer.write("soap.action=submitinfo2"); - writer.write(CR); - writer.write("soap.envelope=" + _soapEnvelopeHead + _soapMessage2 - + _soapEnvelopeTail); - writer.write(CR); - writer.write(CR); - writer.close(); - assertTrue("Config file size is zero", _tmpCfgFile.length() > 0); - } - catch (IOException e) - { - fail("Unable to create the qpidinfo.properties due to: " - + e.getMessage()); - } - } - - private void startSoapServer() throws Exception - { - try - { - _server = new ServerSocket(0); - _port = _server.getLocalPort(); - assertTrue("Server not yet bound.", _port != -1); - - assertNotNull("SocketServer is null", _server); - } - catch (Exception ex) - { - fail("Unable to start the socket server due to: " + ex.getMessage()); - } - - _socketAcceptor = new Thread() - { - public void run() - { - while (true) - { - try - { - Socket socket = _server.accept(); - new ConnectionHandler(socket); - } - catch (IOException e) - { - fail("Error opening the socket in accept mode"); - } - } - } - }; - _socketAcceptor.start(); - System.out.println("*** Socket server started..."); - } - - class ConnectionHandler implements Runnable - { - private Socket _socket; - - public ConnectionHandler(Socket socket) - { - _socket = socket; - Thread t = new Thread(this); - t.start(); - } - - public void run() - { - System.out.println("*** Connection handler running..."); - List buf = new ArrayList(); - String line; - try - { - BufferedReader br = new BufferedReader(new InputStreamReader( - _socket.getInputStream())); - assertNotNull(br); - while ((line = br.readLine()) != null) - { - buf.add(line); - } - br.close(); - System.out.println("*** Received buffer: " + buf); - synchronized (_recv) - { - _recv.add(buf); - } - - System.out.println("*** Latch countdown"); - _latch.countDown(); - } - catch (Exception ex) - { - ex.printStackTrace(); - fail("Exception while reading from the socket"); - } - - } - - } - - public void testInfoPlugin() throws Exception - { - //Start the broker - super.setUp(); - if (!_latch.await(10, TimeUnit.SECONDS)) - { - fail("Timeout awaiting for the latch, upon startup"); - } - - validateResponses("STARTUP"); - - _recv.clear(); - _latch = new CountDownLatch(2); - - stopBroker(); - - if (!_latch.await(10, TimeUnit.SECONDS)) - { - fail("Timeout awaiting for the latch, upon shutdown"); - } - - validateResponses("SHUTDOWN"); - - } - - /** - * Check the responses from the server to ensure they contain the required messages. - * @param action String to match for the SHUTDOWN or STARTUP action. - */ - private void validateResponses(String action) - { - assertTrue("Received less than 2 messages", _recv.size() > 1); - - // Message 1 - assertTrue("Message does not contain Host: localhost:" + _port + "\n" + _recv.get(0), _recv.get(0).contains("Host: localhost:" + _port)); - assertTrue("Message does not contain: User-Agent: Axis2 " + "\n" + _recv.get(0), _recv.get(0).contains("User-Agent: Axis2")); - assertTrue("Message does not contain: SOAPAction: \"urn:submitinfo\"" + "\n" + _recv.get(0).get(4), _recv.get(0).get(4).startsWith("SOAPAction: \"urn:submitinfo")); - assertTrue("Message does not contain '" + action + "' in the soap envelope" + "\n" + _recv.get(0).get(7), _recv.get(0).get(7).contains(action)); - - // Message 2 - assertTrue("Message does not contain Host: localhost:" + _port + "\n" + _recv.get(1), _recv.get(1).contains("Host: localhost:" + _port)); - assertTrue("Message does not contain: User-Agent: Axis2 " + "\n" + _recv.get(1), _recv.get(1).contains("User-Agent: Axis2")); - assertTrue("Message does not contain: SOAPAction: \"urn:submitinfo\"" + "\n" + _recv.get(1).get(4), _recv.get(1).get(4).startsWith("SOAPAction: \"urn:submitinfo")); - assertTrue("Message does not contain '" + action + "' in the soap envelope" + "\n" + _recv.get(1).get(7), _recv.get(1).get(7).contains(action)); - } - -} diff --git a/qpid/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/HttpPosterTest.java b/qpid/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/HttpPosterTest.java deleted file mode 100644 index 4f76fea8ef..0000000000 --- a/qpid/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/HttpPosterTest.java +++ /dev/null @@ -1,107 +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.info.test; - -import java.util.List; -import java.util.Properties; - -import org.apache.qpid.info.util.HttpPoster; -import org.mortbay.jetty.testing.ServletTester; - -import junit.framework.TestCase; - -/* - * This test verifies that the plugin posts correctly to a webserver - * We use an embedded jetty container to mimic the webserver - */ -public class HttpPosterTest extends TestCase -{ - - private ServletTester tester; - - private String baseURL; - - private final String contextPath = "/info"; - - /* - * This method generates a dummy HttpPoster with a dummy body containing a - * single line. The url we are posting to can be controlled by the parameter - * url - * - * @param url - */ - private HttpPoster getHttpPoster(String url) - { - StringBuffer sb = new StringBuffer("test=TEST"); - Properties props = new Properties(); - props.put("http.url", url); - return new HttpPoster(props, sb); - } - - /* - * (non-Javadoc) - * - * @see junit.framework.TestCase#setUp() - */ - protected void setUp() throws Exception - { - tester = new ServletTester(); - tester.setContextPath("/"); - tester.addServlet(InfoServlet.class, contextPath); - baseURL = tester.createSocketConnector(true); - tester.start(); - } - - /* - * (non-Javadoc) - * - * @see junit.framework.TestCase#tearDown() - */ - protected void tearDown() throws Exception - { - super.tearDown(); - tester.stop(); - } - - /* - * This test is posting a string to an embedded Jetty Servlet and captures - * the response message. If the servlet receives the message ok, it will - * print Ok. A failure test is following where we post to a non-existent URL - */ - public void testHttpPoster() throws Exception - { - // Test HttpPoster posts correctly to the servlet - HttpPoster hp = getHttpPoster(baseURL + contextPath); - assertNotNull(hp); - hp.run(); - List response = hp.get_response(); - assertTrue(response.size() > 0); - assertEquals("OK
", response.get(0).toString()); - - // Failure Test - hp = getHttpPoster("http://localhost/nonexistent"); - hp.run(); - response = hp.get_response(); - assertTrue(response.size() == 0); - - } - -} diff --git a/qpid/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/InfoServiceImplTest.java b/qpid/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/InfoServiceImplTest.java deleted file mode 100644 index 9f359582a5..0000000000 --- a/qpid/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/InfoServiceImplTest.java +++ /dev/null @@ -1,63 +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.info.test; - -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -import org.apache.qpid.info.Info; -import org.apache.qpid.info.InfoServiceImpl; - -import junit.framework.TestCase; - -/* - * This test verifies the invoke() method for the info service making sure that the parameters are returned - */ -public class InfoServiceImplTest extends TestCase -{ - - InfoServiceImpl _isi = null; - - @SuppressWarnings("unchecked") - public void testInvoke() - { - _isi = new InfoServiceImpl(); - assertNotNull(_isi); - Info> info = (Info>) _isi - .invoke("START"); - assertNotNull(info); - Properties props = info.toProps(); - assertNotNull(props); - List infoProps = Arrays.asList("java.class.path", - "java.vm.name", "java.class.version", "os.arch", "os.name", - "os.version", "sun.arch.data.model", "user.dir", "user.name", - "user.timezone"); - for (String tag : infoProps) - { - assertNotNull("Info.toProps() does not have the property: " + tag, - props.getProperty(tag)); - } - } - -} diff --git a/qpid/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/InfoServlet.java b/qpid/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/InfoServlet.java deleted file mode 100644 index 6b12a2d80c..0000000000 --- a/qpid/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/InfoServlet.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.apache.qpid.info.test; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.PrintWriter; -import javax.servlet.GenericServlet; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; - -/* - * This is a servlet used by the embedded Jetty to be able to receive http post - * from the info plugin - */ - -public class InfoServlet extends GenericServlet -{ - private static final long serialVersionUID = 1L; - - @Override - public void service(ServletRequest request, ServletResponse response) - throws ServletException, IOException - { - String line; - BufferedReader in = request.getReader(); - while ((line = in.readLine()) != null) - { - System.out.println(line); - } - response.setContentType("text/html"); - PrintWriter out = response.getWriter(); - out.println("OK
\n"); - System.out.println("ServletResponse: OK"); - } - -} \ No newline at end of file diff --git a/qpid/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/InfoTest.java b/qpid/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/InfoTest.java deleted file mode 100644 index bb4965ef1e..0000000000 --- a/qpid/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/InfoTest.java +++ /dev/null @@ -1,112 +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.info.test; - -import java.util.HashMap; -import java.util.Properties; -import junit.framework.TestCase; -import org.apache.qpid.info.Info; - -/* - * This test verifies the toString(), toProps(), toXML() and toStringBuffer() methods of the Info object - * - */ -public class InfoTest extends TestCase -{ - private HashMap _infoPayLoad = null; - - private Info> _info = null; - - protected void setUp() throws Exception - { - super.setUp(); - _infoPayLoad = new HashMap(); - _infoPayLoad.put("test", "Test"); - _info = new Info>(_infoPayLoad); - } - - /* - * Test the conversion toString() of the Info object - */ - public void testToString() - { - assertNotNull("toString() returned null", _info.toString()); - assertEquals("toString() did not return the proper string", - "test=Test\n", _info.toString()); - } - - /* - * Test the conversion toProps() of the Info object - */ - public void testToProps() - { - Properties props = new Properties(); - props.put("test", "Test"); - assertNotNull("toProperties() returned null", _info.toProps()); - assertEquals("toProperties not returned the proper object", props, _info - .toProps()); - } - - /* - * Test the conversion toStringBuffer() of the Info object - */ - public void testToStringBuffer() - { - StringBuffer sb = new StringBuffer("test=Test\n"); - assertNotNull(_info.toStringBuffer()); - assertEquals(sb.toString(), _info.toStringBuffer().toString()); - } - - /* - * Test conversion toXML() of the info object - */ - public void testToXML() - { - String INDENT = " "; - StringBuffer sb = new StringBuffer(); - sb.append("\n"); - sb.append("\n"); - sb.append("\n"); - sb.append(INDENT + "Test\n"); - sb.append("\n"); - sb.append("\n"); - assertEquals("toString() does not return the proper string", _info - .toXML().toString(), sb.toString()); - } - - /* - * Test the conversion toMap() of the Info object - */ - public void testToMap() - { - HashMap thm = _info.toMap(); - assertFalse("toMap() returned empty map", thm.isEmpty()); - assertEquals("testToMap did not returned 1", 1, thm.size()); - assertTrue("toMap() returned a map not containing expected key: test", - thm.containsKey("test")); - assertTrue( - "toMap() returned a map not containing the value for key test: Test", - thm.containsValue("Test")); - - } - -} diff --git a/qpid/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/IniFileReaderTest.java b/qpid/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/IniFileReaderTest.java deleted file mode 100644 index 77ecaa2176..0000000000 --- a/qpid/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/IniFileReaderTest.java +++ /dev/null @@ -1,136 +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.info.test; - -import junit.framework.TestCase; -import org.apache.qpid.info.util.IniFileReader; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.util.Map; -import java.util.Properties; - -/** - * Test the Loading of the ini file reader by first writing - * out a correct ini file. - */ -public class IniFileReaderTest extends TestCase -{ - - public void testLoad() - { - IniFileReader ifr = new IniFileReader(); - File iniFile = null; - try - { - iniFile = File.createTempFile("temp", "ini"); - iniFile.deleteOnExit(); - BufferedWriter writer = new BufferedWriter(new FileWriter(iniFile)); - writer.write("# Global Comment1\n"); - writer.write("globalprop1=globalval1\n"); - writer.write("globalprop2=globalval2\n"); - writer.write("\n"); - writer.write("[Section1] # Comment on Section\n"); - writer.write("key1=val1 # Comment on Value\n"); - writer.write("key2=val2\n"); - writer.write("\n"); - writer.write("#Section2 Comment\n"); - writer.write("[Section2]\n"); - writer.write("key3=val3\n"); - writer.write("key4=val4\n"); - writer.write("key5=val5\n"); - writer.write("\n"); - writer.write("[Section3]\n"); - writer.write("key6=val6\n"); - writer.write("key7=val7\n"); - writer.write("\n"); - writer.close(); - } - catch (IOException e) - { - e.printStackTrace(); - fail("Unable to create temporary File"); - } - ifr.load(iniFile.getAbsolutePath()); - Map sections = ifr.getSections(); - assertNotNull("Sections not null", sections); - assertEquals("Have 4 sections", sections.keySet().size(), 4); - assertTrue("Get globalprop1", sections.get("").getProperty("globalprop1").equals("globalval1")); - assertTrue("Get globalprop2", sections.get("").getProperty("globalprop2").equals("globalval2")); - assertNotNull("Section1 not null", sections.get("Section1")); - assertEquals("Section1 has 2 properties", sections.get("Section1").size(), 2); - assertTrue("Section1 key1 has val1", sections.get("Section1").getProperty("key1").equals("val1")); - assertTrue("Section1 key2 has val2", sections.get("Section1").getProperty("key2").equals("val2")); - assertEquals("Section2 has 3 properties", sections.get("Section2").size(), 3); - assertTrue("Section2 key3 has val3", sections.get("Section2").getProperty("key3").equals("val3")); - assertTrue("Section2 key4 has val4", sections.get("Section2").getProperty("key4").equals("val4")); - assertTrue("Section2 key5 has val5", sections.get("Section2").getProperty("key5").equals("val5")); - assertEquals("Section3 has 2 properties", sections.get("Section3").size(), 2); - assertTrue("Section3 key6 has val6", sections.get("Section3").getProperty("key6").equals("val6")); - assertTrue("Section3 key7 has val7", sections.get("Section3").getProperty("key7").equals("val7")); - } - - /** - * Test to ensure that the loading of a file with an unclosed section header - * fails to parse. - * - * Section needs to be fully enclosed in square brackets '[]' - */ - public void testIncompleteSection1Load() - { - IniFileReader ifr = new IniFileReader(); - File iniFile = null; - try - { - iniFile = File.createTempFile(getName(), "ini"); - iniFile.deleteOnExit(); - BufferedWriter writer = new BufferedWriter(new FileWriter(iniFile)); - writer.write("# Global Comment1\n"); - writer.write("globalprop1=globalval1\n"); - writer.write("globalprop2=globalval2\n"); - writer.write("\n"); - writer.write("[Section1\n"); // Note '[Section1' not complete - writer.write("key1=val1\n"); - writer.write("key2=val2\n"); - writer.write("\n"); - writer.close(); - } - catch (IOException e) - { - e.printStackTrace(); - fail("Unable to create temporary File"); - } - try - { - ifr.load(iniFile.getAbsolutePath()); - fail("File should fail to parse"); - } - catch (IllegalArgumentException iae) - { - assertEquals("Incorrect Exception", "Section1 is not closed", iae.getMessage()); - } - - } - -} diff --git a/qpid/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/SoapClientTest.java b/qpid/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/SoapClientTest.java deleted file mode 100644 index a3d993a39f..0000000000 --- a/qpid/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/SoapClientTest.java +++ /dev/null @@ -1,208 +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.info.test; - -import junit.framework.TestCase; -import org.apache.qpid.info.util.SoapClient; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.ServerSocket; -import java.net.Socket; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Properties; - -public class SoapClientTest extends TestCase -{ - - private int _port; - - private final String _hostName = "localhost"; - - private final String _urlPath = "/testSoap"; - - private ServerSocket _server = null; - - /* - * Generate a soap client from a custom URL, hostname, port and soap context - * path to be derived - */ - private SoapClient getSoapClient() - { - Properties destprops = new Properties(); - destprops.setProperty("soap.hostname", _hostName); - destprops.setProperty("soap.port", _port + ""); - destprops.setProperty("soap.urlpath", _urlPath); - destprops.setProperty("soap.envelope", "@IP"); - destprops.setProperty("soap.action", "send"); - HashMap soapmap = new HashMap(); - soapmap.put("IP", "127.0.0.1"); - return new SoapClient(soapmap, destprops); - } - - /* - * A connection handler class that verifies the correct message is received - * - */ - class ConnectionHandler implements Runnable - { - private Socket socket; - - public ConnectionHandler(Socket socket) - { - this.socket = socket; - Thread t = new Thread(this); - t.start(); - } - - public void run() - { - String line; - final List response = new ArrayList(); - try - { - BufferedReader br = new BufferedReader(new InputStreamReader( - socket.getInputStream())); - assertNotNull(br); - while ((line = br.readLine()) != null) - { - response.add(line); - } - br.close(); - } - catch (Exception ex) - { - ex.printStackTrace(); - fail("Exception while reading from the socket"); - } - assertTrue(response.contains("127.0.0.1")); - assertTrue(response.contains("SOAPAction: \"urn:send\"")); - assertTrue(response - .contains("Content-Type: text/xml; charset=\"utf-8\"")); - assertTrue(response.contains("Host: localhost" + _port)); - assertTrue(response.contains("User-Agent: Axis2")); - } - - } - - /* - * Test that the SOAP client sends the expected data to the socket We mock a - * simple SOAP envelope: 127.0.0.1 - */ - public void testSoapClient() throws Exception - { - // - try - { - _server = new ServerSocket(0); - _port = _server.getLocalPort(); - assertTrue("Server is not yet bound to a port", _port != -1); - assertNotNull(_server); - } - catch (Exception ex) - { - ex.printStackTrace(); - fail("Unable to start the socket server"); - } - - Thread _socketAcceptor = new Thread() - { - public void run() - { - try - { - Socket socket = _server.accept(); - new ConnectionHandler(socket); - } - catch (IOException e) - { - e.printStackTrace(); - } - } - }; - _socketAcceptor.start(); - // Sleep for 1 second to allow the ServerSocket readiness - Thread.sleep(1000); - SoapClient sc = getSoapClient(); - assertNotNull(sc); - sc.sendSOAPMessage(); - - _socketAcceptor.join(2000); - - assertFalse("Socket Acceptor not stopped.", _socketAcceptor.isAlive()); - } - - /** - * Test SoapClient correctly clears previously set values - */ - public void testSoapClientXMLData() - { - SoapClient sc = getSoapClient(); - - StringBuffer initial = new StringBuffer("Initial Value"); - - sc.setXMLData(initial); - - assertEquals("getXMLData is not set with initial value", - initial.toString(), sc.getXMLData().toString()); - - - StringBuffer sb = new StringBuffer(""); - sc.setXMLData(sb); - assertEquals(sc.getXMLData().length(), sb.length()); - assertEquals("getXMLData does not return the same StringBuffer set by setXMLData", - sb.toString(), sc.getXMLData().toString()); - } - - /** - * Test that variable replacement is performed on the soap.envelope. - * Create dummy soap message and validate that the variable have been replaced. - */ - public void testReplaceVariablesMap() - { - Properties props = new Properties(); - // Add dummy values as required to create a soap message - props.setProperty("soap.hostname", _hostName); - props.setProperty("soap.port", "0"); - props.setProperty("soap.urlpath", _urlPath); - props.setProperty("soap.action", "send"); - - /// The envelope is what we care about - props.setProperty("soap.envelope", "@IP:@PORT"); - HashMap soapmap = new HashMap(); - - /// Variables that should be replaced. - final String ip = "127.0.0.1"; - soapmap.put("IP", ip); - final String port = "8080"; - soapmap.put("PORT", port); - - SoapClient sc = new SoapClient(soapmap, props); - assertNotNull("SoapClient is null", sc); - - assertTrue("Replace variables did not work as expected", ("" + ip + ":" + port + "").equals(sc.getXMLData().toString())); - } - -} diff --git a/qpid/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/SystemInfoTest.java b/qpid/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/SystemInfoTest.java deleted file mode 100644 index 6cb8e3a90a..0000000000 --- a/qpid/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/SystemInfoTest.java +++ /dev/null @@ -1,56 +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.info.test; - -import junit.framework.TestCase; -import org.apache.qpid.info.SystemInfo; - -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -/** Test the SystemInfo component */ -public class SystemInfoTest extends TestCase -{ - - /** - * Ensure the list of required properties are returned by the - * SystemInfo.getInfo call - */ - public void testGetInfo() - { - Map sysInfoMap = SystemInfo.getInfo(); - assertNotNull("SystemInfo.getInfo() returned null", sysInfoMap); - List sysInfoProps = Arrays.asList( - "java.class.path", - "java.vm.name", "java.class.version", "os.arch", "os.name", - "os.version", "sun.arch.data.model", "user.dir", "user.name", - "user.timezone", "hostname", "ip", "CPUCores", "Maximum_Memory", - "Free_Memory"); - - for (String tag : sysInfoProps) - { - assertNotNull("Map does not contain the tag: " + tag, sysInfoMap.get(tag)); - } - } - -} \ No newline at end of file diff --git a/qpid/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/XMLWriterTest.java b/qpid/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/XMLWriterTest.java deleted file mode 100644 index f352226361..0000000000 --- a/qpid/java/broker-plugins/experimental/info/src/test/java/org/apache/qpid/info/test/XMLWriterTest.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.info.test; - -import junit.framework.TestCase; -import org.apache.qpid.info.util.XMLWriter; - -import java.util.HashMap; - -/* - * This test verifies the XML writer custom class operations - */ - -public class XMLWriterTest extends TestCase -{ - - private XMLWriter xw = null; - - /** Test constructor arg is returned via getXML() */ - public void testXMLWriter() - { - StringBuffer input = new StringBuffer("Test"); - xw = new XMLWriter(input); - assertNotNull("XMLWriter could not instantiate", xw); - assertEquals("XMLWriter.getXML() failed", input, xw.getXML()); - } - - /** Test header generation */ - public void testWriteXMLHeader() - { - xw = new XMLWriter(new StringBuffer()); - assertNotNull(xw); - xw.writeXMLHeader(); - assertEquals("XMLWriter.writeXMLHeader(...) failed", "\n", xw.getXML().toString()); - } - - /** Test tag created and written correctly */ - public void testWriteTag() - { - String INDENT = " "; - xw = new XMLWriter(new StringBuffer()); - assertNotNull("XMLWriter could not instantiate", xw); - xw.writeTag("test", new HashMap(), "TEST"); - assertEquals("XMLWriter.writeTag(...) failed", "\n" + INDENT + "TEST\n" + "\n", xw.getXML() - .toString()); - } - - /** Test tag created and written correctly */ - public void testWriteTagWithNullAttribute() - { - String INDENT = " "; - xw = new XMLWriter(new StringBuffer()); - assertNotNull("XMLWriter could not instantiate", xw); - xw.writeTag("test", null, "TEST"); - assertEquals("XMLWriter.writeTag(...) failed", "\n" + INDENT + "TEST\n" + "\n", xw.getXML() - .toString()); - } - - /** Test tag created and written correctly with attribute */ - public void testWriteTagWithAttribute() - { - String INDENT = " "; - xw = new XMLWriter(new StringBuffer()); - assertNotNull("XMLWriter could not instantiate", xw); - HashMap attr = new HashMap(); - attr.put("id", "1"); - - xw.writeTag("test", attr, "TEST"); - assertEquals("XMLWriter.writeTag(...) failed", "\n" + INDENT + "TEST\n" + "\n", xw.getXML() - .toString()); - } - - /** Test open tag with an empty attribute map. Just creates an open tag */ - public void testWriteOpenTag() - { - xw = new XMLWriter(new StringBuffer()); - assertNotNull(xw); - HashMap attr = new HashMap(); - xw.writeOpenTag("test", attr); - assertEquals("XMLWriter.writeOpenTag(...) failed", "\n", xw.getXML().toString()); - } - - /** Test open tag with a null attribute map. Just creates an open tag */ - public void testNullAtrributeOnTag() - { - xw = new XMLWriter(new StringBuffer()); - assertNotNull(xw); - xw.writeOpenTag("test", null); - assertEquals("XMLWriter.writeOpenTag(...) failed", "\n", xw.getXML().toString()); - } - - /** Test that setting an attribute value on the tag is correctly outputted. */ - public void testAtrributeOnTag() - { - xw = new XMLWriter(new StringBuffer()); - assertNotNull(xw); - HashMap attr = new HashMap(); - - attr.put("id", "1"); - xw.writeOpenTag("test1", attr); - assertEquals("XMLWriter.writeOpenTag(...) failed", "\n", xw.getXML().toString()); - } - - /** Test Close Tag is correctly written */ - public void testWriteCloseTag() - { - xw = new XMLWriter(new StringBuffer()); - assertNotNull(xw); - xw.writeCloseTag("test"); - assertEquals("\n", xw.getXML().toString()); - } - -} diff --git a/qpid/java/broker-plugins/experimental/shutdown/src/main/java/org/apache/qpid/shutdown/ShutdownMBean.java b/qpid/java/broker-plugins/experimental/shutdown/src/main/java/org/apache/qpid/shutdown/ShutdownMBean.java index 48d2eab8df..5c54fb3e21 100644 --- a/qpid/java/broker-plugins/experimental/shutdown/src/main/java/org/apache/qpid/shutdown/ShutdownMBean.java +++ b/qpid/java/broker-plugins/experimental/shutdown/src/main/java/org/apache/qpid/shutdown/ShutdownMBean.java @@ -19,6 +19,8 @@ */ package org.apache.qpid.shutdown; +import javax.management.MBeanOperationInfo; + import org.apache.qpid.management.common.mbeans.annotations.MBeanOperation; import org.apache.qpid.management.common.mbeans.annotations.MBeanOperationParameter; @@ -34,7 +36,7 @@ public interface ShutdownMBean /** * Broker will be shut down immediately. */ - @MBeanOperation(name="shutdown", description="Shut down immediately") + @MBeanOperation(name="shutdown", description="Shut down immediately", impact = MBeanOperationInfo.ACTION) public void shutdown(); /** @@ -42,7 +44,7 @@ public interface ShutdownMBean * * @param delay the number of ms to wait */ - @MBeanOperation(name="shutdown", description="Shutdown after the specified delay (ms)") + @MBeanOperation(name="shutdown", description="Shutdown after the specified delay (ms)", impact = MBeanOperationInfo.ACTION) public void shutdown(@MBeanOperationParameter(name="when", description="delay (ms)")long delay); /** @@ -50,6 +52,6 @@ public interface ShutdownMBean * * @param when the date and time to shutdown */ - @MBeanOperation(name="shutdownAt", description="Shutdown at the specified date and time (yyyy/MM/dd HH:mm:ss)") + @MBeanOperation(name="shutdownAt", description="Shutdown at the specified date and time (yyyy/MM/dd HH:mm:ss)", impact = MBeanOperationInfo.ACTION) public void shutdownAt(@MBeanOperationParameter(name="when", description="shutdown date/time (yyyy/MM/dd HH:mm:ss)")String when); } diff --git a/qpid/java/broker-plugins/experimental/shutdown/src/main/java/shutdown.bnd b/qpid/java/broker-plugins/experimental/shutdown/src/main/java/shutdown.bnd index c9e1371732..60af4b89e8 100755 --- a/qpid/java/broker-plugins/experimental/shutdown/src/main/java/shutdown.bnd +++ b/qpid/java/broker-plugins/experimental/shutdown/src/main/java/shutdown.bnd @@ -17,7 +17,7 @@ # under the License. # -ver: 0.15.0 +ver: 0.17.0 Bundle-SymbolicName: qpid-shutdown-plugin Bundle-Version: ${ver} diff --git a/qpid/java/broker-plugins/extras/src/main/java/org/apache/qpid/extras/Activator.java b/qpid/java/broker-plugins/extras/src/main/java/org/apache/qpid/extras/Activator.java index ca6c05a435..fa0ffb5045 100644 --- a/qpid/java/broker-plugins/extras/src/main/java/org/apache/qpid/extras/Activator.java +++ b/qpid/java/broker-plugins/extras/src/main/java/org/apache/qpid/extras/Activator.java @@ -20,11 +20,12 @@ */ package org.apache.qpid.extras; +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; + import org.apache.qpid.extras.exchanges.diagnostic.DiagnosticExchangeType; import org.apache.qpid.extras.exchanges.example.TestExchangeType; import org.apache.qpid.server.exchange.ExchangeType; -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; /** * diff --git a/qpid/java/broker-plugins/extras/src/main/java/org/apache/qpid/extras/exchanges/diagnostic/DiagnosticExchange.java b/qpid/java/broker-plugins/extras/src/main/java/org/apache/qpid/extras/exchanges/diagnostic/DiagnosticExchange.java index 5d2c0dd5b2..6e1ea25f26 100644 --- a/qpid/java/broker-plugins/extras/src/main/java/org/apache/qpid/extras/exchanges/diagnostic/DiagnosticExchange.java +++ b/qpid/java/broker-plugins/extras/src/main/java/org/apache/qpid/extras/exchanges/diagnostic/DiagnosticExchange.java @@ -20,14 +20,8 @@ */ package org.apache.qpid.extras.exchanges.diagnostic; -import java.util.ArrayList; -import java.util.Map; - -import javax.management.JMException; -import javax.management.openmbean.OpenDataException; -import javax.management.openmbean.TabularData; - import org.apache.log4j.Logger; + import org.apache.qpid.AMQException; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.framing.FieldTable; @@ -41,6 +35,12 @@ import org.apache.qpid.server.message.InboundMessage; import org.apache.qpid.server.queue.AMQQueue; import org.apache.qpid.server.virtualhost.VirtualHost; +import javax.management.JMException; +import javax.management.openmbean.OpenDataException; +import javax.management.openmbean.TabularData; +import java.util.ArrayList; +import java.util.Map; + /** * This is a special diagnostic exchange type which doesn't actually do anything * with messages. When it receives a message, it writes information about the @@ -54,9 +54,6 @@ public class DiagnosticExchange extends AbstractExchange public static final AMQShortString DIAGNOSTIC_EXCHANGE_CLASS = new AMQShortString("x-diagnostic"); public static final AMQShortString DIAGNOSTIC_EXCHANGE_NAME = new AMQShortString("diagnostic"); - /** The logger */ - //private static final Logger _logger = Logger.getLogger(DiagnosticExchange.class); - /** * MBean class implementing the management interfaces. */ @@ -83,7 +80,6 @@ public class DiagnosticExchange extends AbstractExchange * @returns null * TODO or can there? Could this actually return all the information in one easy to read table? */ - @Override public TabularData bindings() throws OpenDataException { return null; @@ -197,13 +193,6 @@ public class DiagnosticExchange extends AbstractExchange public ArrayList doRoute(InboundMessage payload) { //TODO shouldn't modify messages... perhaps put a new message on the queue? - /* - Long value = new Long(SizeOf.getUsedMemory()); - AMQShortString key = new AMQShortString("memory"); - FieldTable headers = ((BasicContentHeaderProperties)payload.getMessageHeader().properties).getHeaders(); - headers.put(key, value); - ((BasicContentHeaderProperties)payload.getMessageHeader().properties).setHeaders(headers); - */ AMQQueue q = getQueueRegistry().getQueue(new AMQShortString("diagnosticqueue")); ArrayList queues = new ArrayList(); queues.add(q); diff --git a/qpid/java/broker-plugins/extras/src/main/java/org/apache/qpid/extras/exchanges/example/TestExchange.java b/qpid/java/broker-plugins/extras/src/main/java/org/apache/qpid/extras/exchanges/example/TestExchange.java index def0b3f91a..cf79924f3d 100644 --- a/qpid/java/broker-plugins/extras/src/main/java/org/apache/qpid/extras/exchanges/example/TestExchange.java +++ b/qpid/java/broker-plugins/extras/src/main/java/org/apache/qpid/extras/exchanges/example/TestExchange.java @@ -21,11 +21,6 @@ package org.apache.qpid.extras.exchanges.example; */ -import java.util.ArrayList; -import java.util.Collection; -import java.util.Map; -import java.util.UUID; - import org.apache.qpid.AMQException; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.framing.FieldTable; @@ -41,6 +36,11 @@ import org.apache.qpid.server.queue.AMQQueue; import org.apache.qpid.server.queue.BaseQueue; import org.apache.qpid.server.virtualhost.VirtualHost; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Map; +import java.util.UUID; + public class TestExchange implements Exchange { @@ -80,6 +80,11 @@ public class TestExchange implements Exchange return false; } + public boolean isBound(String bindingKey, Map arguments, AMQQueue queue) + { + return false; + } + public boolean isBound(String bindingKey) { return false; diff --git a/qpid/java/broker-plugins/extras/src/test/java/org/apache/qpid/server/plugins/ExtrasTest.java b/qpid/java/broker-plugins/extras/src/test/java/org/apache/qpid/server/plugins/ExtrasTest.java index db3ebfd4e1..458f9a1846 100644 --- a/qpid/java/broker-plugins/extras/src/test/java/org/apache/qpid/server/plugins/ExtrasTest.java +++ b/qpid/java/broker-plugins/extras/src/test/java/org/apache/qpid/server/plugins/ExtrasTest.java @@ -20,6 +20,7 @@ package org.apache.qpid.server.plugins; import junit.framework.TestCase; import org.apache.commons.configuration.PropertiesConfiguration; + import org.apache.qpid.server.configuration.ServerConfiguration; import org.apache.qpid.server.exchange.ExchangeType; import org.apache.qpid.server.registry.ApplicationRegistry; @@ -35,7 +36,7 @@ public class ExtrasTest extends TestCase private static final String PLUGIN_DIRECTORY = System.getProperty("example.plugin.target"); private static final String CACHE_DIRECTORY = System.getProperty("example.cache.target"); - IApplicationRegistry _registry; + private IApplicationRegistry _registry; @Override public void setUp() throws Exception diff --git a/qpid/java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/config/FirewallRule.java b/qpid/java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/config/FirewallRule.java index f257b58867..ecec4b0cec 100644 --- a/qpid/java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/config/FirewallRule.java +++ b/qpid/java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/config/FirewallRule.java @@ -20,6 +20,9 @@ */ package org.apache.qpid.server.security.access.config; +import org.apache.qpid.server.security.Result; +import org.apache.qpid.util.NetMatcher; + import java.net.InetAddress; import java.util.List; import java.util.concurrent.Callable; @@ -27,12 +30,8 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; import java.util.regex.Pattern; -import org.apache.qpid.server.security.Result; -import org.apache.qpid.util.NetMatcher; - public class FirewallRule { public static final String ALLOW = "ALLOW"; diff --git a/qpid/java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/plugins/Firewall.java b/qpid/java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/plugins/Firewall.java index a6ea9d261e..40a65fddba 100644 --- a/qpid/java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/plugins/Firewall.java +++ b/qpid/java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/plugins/Firewall.java @@ -20,11 +20,9 @@ */ package org.apache.qpid.server.security.access.plugins; -import java.net.InetAddress; -import java.net.InetSocketAddress; - import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.ConfigurationException; + import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin; import org.apache.qpid.server.security.AbstractPlugin; import org.apache.qpid.server.security.Result; @@ -35,6 +33,9 @@ import org.apache.qpid.server.security.access.Operation; import org.apache.qpid.server.security.access.config.FirewallException; import org.apache.qpid.server.security.access.config.FirewallRule; +import java.net.InetAddress; +import java.net.InetSocketAddress; + public class Firewall extends AbstractPlugin { public static final SecurityPluginFactory FACTORY = new SecurityPluginFactory() @@ -114,7 +115,7 @@ public class Firewall extends AbstractPlugin public void configure(ConfigurationPlugin config) { super.configure(config); - FirewallConfiguration firewallConfiguration = (FirewallConfiguration) _config; + FirewallConfiguration firewallConfiguration = (FirewallConfiguration) getConfig(); // Get default action _default = firewallConfiguration.getDefaultAction(); diff --git a/qpid/java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/plugins/FirewallActivator.java b/qpid/java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/plugins/FirewallActivator.java index c20bba8d2c..1669352085 100644 --- a/qpid/java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/plugins/FirewallActivator.java +++ b/qpid/java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/plugins/FirewallActivator.java @@ -23,10 +23,9 @@ package org.apache.qpid.server.security.access.plugins; import org.apache.qpid.server.configuration.plugins.ConfigurationPluginFactory; import org.apache.qpid.server.security.SecurityPluginActivator; import org.apache.qpid.server.security.SecurityPluginFactory; -import org.osgi.framework.BundleActivator; /** - * The OSGi {@link BundleActivator} for {@link Firewall}. + * The OSGi {@link org.osgi.framework.BundleActivator} for {@link Firewall}. */ public class FirewallActivator extends SecurityPluginActivator { diff --git a/qpid/java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/plugins/FirewallConfiguration.java b/qpid/java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/plugins/FirewallConfiguration.java index b10656d622..010d1652f0 100644 --- a/qpid/java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/plugins/FirewallConfiguration.java +++ b/qpid/java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/plugins/FirewallConfiguration.java @@ -20,21 +20,22 @@ */ package org.apache.qpid.server.security.access.plugins; -import java.util.Arrays; -import java.util.List; - import org.apache.commons.configuration.CompositeConfiguration; import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.XMLConfiguration; + import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin; import org.apache.qpid.server.configuration.plugins.ConfigurationPluginFactory; import org.apache.qpid.server.security.Result; import org.apache.qpid.server.security.access.config.FirewallRule; +import java.util.Arrays; +import java.util.List; + public class FirewallConfiguration extends ConfigurationPlugin { - CompositeConfiguration _finalConfig; + private CompositeConfiguration _finalConfig; public static final ConfigurationPluginFactory FACTORY = new ConfigurationPluginFactory() { @@ -63,7 +64,7 @@ public class FirewallConfiguration extends ConfigurationPlugin public Result getDefaultAction() { - String defaultAction = _configuration.getString("[@default-action]"); + String defaultAction = getConfig().getString("[@default-action]"); if (defaultAction == null) { return Result.ABSTAIN; @@ -84,8 +85,8 @@ public class FirewallConfiguration extends ConfigurationPlugin public void validateConfiguration() throws ConfigurationException { // Valid Configuration either has xml links to new files - _finalConfig = new CompositeConfiguration(_configuration); - List subFiles = _configuration.getList("xml[@fileName]"); + _finalConfig = new CompositeConfiguration(getConfig()); + List subFiles = getConfig().getList("xml[@fileName]"); for (Object subFile : subFiles) { _finalConfig.addConfiguration(new XMLConfiguration((String) subFile)); @@ -93,7 +94,7 @@ public class FirewallConfiguration extends ConfigurationPlugin // all rules must have an access attribute or a default value if (_finalConfig.getList("rule[@access]").size() == 0 && - _configuration.getString("[@default-action]") == null) + getConfig().getString("[@default-action]") == null) { throw new ConfigurationException("No rules or default-action found in firewall configuration."); } diff --git a/qpid/java/broker-plugins/firewall/src/test/java/org/apache/qpid/server/security/access/FirewallConfigurationTest.java b/qpid/java/broker-plugins/firewall/src/test/java/org/apache/qpid/server/security/access/FirewallConfigurationTest.java index e078675efc..8969363979 100644 --- a/qpid/java/broker-plugins/firewall/src/test/java/org/apache/qpid/server/security/access/FirewallConfigurationTest.java +++ b/qpid/java/broker-plugins/firewall/src/test/java/org/apache/qpid/server/security/access/FirewallConfigurationTest.java @@ -20,18 +20,18 @@ */ package org.apache.qpid.server.security.access; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.RandomAccessFile; -import java.net.InetSocketAddress; - import org.apache.qpid.server.registry.ApplicationRegistry; import org.apache.qpid.server.registry.ConfigurationFileApplicationRegistry; import org.apache.qpid.server.virtualhost.VirtualHost; import org.apache.qpid.server.virtualhost.VirtualHostRegistry; import org.apache.qpid.test.utils.QpidTestCase; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.net.InetSocketAddress; + public class FirewallConfigurationTest extends QpidTestCase { @Override diff --git a/qpid/java/broker-plugins/firewall/src/test/java/org/apache/qpid/server/security/access/FirewallPluginTest.java b/qpid/java/broker-plugins/firewall/src/test/java/org/apache/qpid/server/security/access/FirewallPluginTest.java index 00077d9d9c..2004852c48 100644 --- a/qpid/java/broker-plugins/firewall/src/test/java/org/apache/qpid/server/security/access/FirewallPluginTest.java +++ b/qpid/java/broker-plugins/firewall/src/test/java/org/apache/qpid/server/security/access/FirewallPluginTest.java @@ -18,15 +18,9 @@ */ package org.apache.qpid.server.security.access; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.SocketAddress; - import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.XMLConfiguration; + import org.apache.qpid.server.configuration.ServerConfiguration; import org.apache.qpid.server.registry.ApplicationRegistry; import org.apache.qpid.server.security.Result; @@ -35,6 +29,13 @@ import org.apache.qpid.server.security.access.plugins.FirewallConfiguration; import org.apache.qpid.server.util.TestApplicationRegistry; import org.apache.qpid.test.utils.QpidTestCase; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.SocketAddress; + public class FirewallPluginTest extends QpidTestCase { public class RuleInfo diff --git a/qpid/java/broker/bin/create-example-ssl-stores.bat b/qpid/java/broker/bin/create-example-ssl-stores.bat deleted file mode 100644 index 5419c098d5..0000000000 --- a/qpid/java/broker/bin/create-example-ssl-stores.bat +++ /dev/null @@ -1,36 +0,0 @@ -@REM -@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 - -@REM Create example keystore for broker and trust store for client/management console. -@REM -@REM Use generated qpid.keystore as the brokers keystore -@REM Use generated qpid.truststore as client/consoles truststore -@REM All passwords have value: password - -@REM Create Broker Keystore: -keytool -genkey -alias qpidBroker -keyalg RSA -validity 365 -keystore qpid.keystore -storepass password -keypass password -dname "CN=hostname, OU=OrgUnit, O=Org, L=City, C=US" - -@REM Export Self Signed Cert: -keytool -export -alias qpidBroker -keystore qpid.keystore -file qpidBroker.cer -storepass password - -@REM Import Broker Cert Into MC TrustStore: -keytool -import -alias qpidBrokerCert -file qpidBroker.cer -keystore qpid.truststore -storepass password -noprompt - -@REM Delete the cert -del qpidBroker.cer \ No newline at end of file diff --git a/qpid/java/broker/bin/create-example-ssl-stores.sh b/qpid/java/broker/bin/create-example-ssl-stores.sh deleted file mode 100755 index bfcb3dfecf..0000000000 --- a/qpid/java/broker/bin/create-example-ssl-stores.sh +++ /dev/null @@ -1,38 +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. -# - -# Create example keystore for broker and trust store for client/management console. -# -# Use generated qpid.keystore as the brokers keystore -# Use generated qpid.truststore as client/consoles truststore -# All passwords have value: password - -#Create Broker Keystore: -keytool -genkey -alias qpidBroker -keyalg RSA -validity 365 -keystore qpid.keystore \ --storepass password -keypass password -dname "CN=hostname, OU=OrgUnit, O=Org, L=City, C=US" - -#Export Self Signed Cert: -keytool -export -alias qpidBroker -keystore qpid.keystore -file qpidBroker.cer -storepass password - -#Import Broker Cert Into MC TrustStore: -keytool -import -alias qpidBrokerCert -file qpidBroker.cer -keystore qpid.truststore -storepass password -noprompt - -#Delete the cert -rm qpidBroker.cer diff --git a/qpid/java/broker/bin/qpid-passwd b/qpid/java/broker/bin/qpid-passwd index f432e00ab8..69246974fa 100755 --- a/qpid/java/broker/bin/qpid-passwd +++ b/qpid/java/broker/bin/qpid-passwd @@ -18,9 +18,9 @@ # under the License. # -WHEREAMI=`dirname $0` if [ -z "$QPID_HOME" ]; then - export QPID_HOME=`cd $WHEREAMI/../ && pwd` + WHEREAMI=`dirname "$0"` + export QPID_HOME=`cd "$WHEREAMI/../" && pwd` fi # Set classpath to include Qpid jar with all required jars in manifest @@ -32,4 +32,4 @@ export JAVA=java \ JAVA_MEM=-Xmx1024m \ QPID_CLASSPATH=$QPID_LIBS -. ${QPID_HOME}/bin/qpid-run org.apache.qpid.tools.security.Passwd "$@" +. "${QPID_HOME}/bin/qpid-run" org.apache.qpid.tools.security.Passwd "$@" diff --git a/qpid/java/broker/build.xml b/qpid/java/broker/build.xml index 4a42e5cdb8..9e8bf12f18 100644 --- a/qpid/java/broker/build.xml +++ b/qpid/java/broker/build.xml @@ -34,14 +34,7 @@ - - - - - - + diff --git a/qpid/java/broker/etc/broker_example.acl b/qpid/java/broker/etc/broker_example.acl index 93955bb7f9..aae4ee3162 100644 --- a/qpid/java/broker/etc/broker_example.acl +++ b/qpid/java/broker/etc/broker_example.acl @@ -24,15 +24,32 @@ #Define a 'messaging-users' group with users 'client' and 'server' in it GROUP messaging-users client server + ### MANAGEMENT #### -#Allow 'guest' to perform read operations on the Serverinformation mbean and view logger levels -ACL ALLOW-LOG guest ACCESS METHOD component="ServerInformation" -ACL ALLOW-LOG guest ACCESS METHOD component="LoggingManagement" name="viewEffectiveRuntimeLoggerLevels" +# Allow everyone to perform read operations on the ServerInformation mbean +# This is used for items such as querying the management API and broker release versions. +ACL ALLOW-LOG ALL ACCESS METHOD component="ServerInformation" -#Allow 'admin' all management operations +# Allow 'admin' all management operations ACL ALLOW-LOG admin ALL METHOD +# Deny access to Shutdown, UserManagement, ConfigurationManagement and LoggingManagement for all other users +# You could grant specific users access to these beans by adding ALLOW-LOG rules above for them +ACL DENY-LOG ALL ACCESS METHOD component="Shutdown" +ACL DENY-LOG ALL ACCESS METHOD component="UserManagement" +ACL DENY-LOG ALL ACCESS METHOD component="ConfigurationManagement" +ACL DENY-LOG ALL ACCESS METHOD component="LoggingManagement" + +# Allow 'guest' to view logger levels, and use getter methods on LoggingManagement +# These are examples of redundant rules! The DENY-LOG rule above will be invoked +# first and will deny the access to all methods of LoggingManagement for guest +ACL ALLOW-LOG guest ACCESS METHOD component="LoggingManagement" name="viewEffectiveRuntimeLoggerLevels" +ACL ALLOW-LOG guest ACCESS METHOD component="LoggingManagement" name="get*" + +# Allow everyone to perform all read operations on the mbeans not listened in the DENY-LOG rules above +ACL ALLOW-LOG ALL ACCESS METHOD + ### MESSAGING ### #Example permissions for request-response based messaging. diff --git a/qpid/java/broker/etc/config.xml b/qpid/java/broker/etc/config.xml index 25fda69f68..e1aacd43b5 100644 --- a/qpid/java/broker/etc/config.xml +++ b/qpid/java/broker/etc/config.xml @@ -53,17 +53,13 @@ false - + ${conf}/qpid.keystore password - 65535 - false - false en_US diff --git a/qpid/java/broker/src/main/grammar/SelectorParser.jj b/qpid/java/broker/src/main/grammar/SelectorParser.jj deleted file mode 100644 index c9e01cd01f..0000000000 --- a/qpid/java/broker/src/main/grammar/SelectorParser.jj +++ /dev/null @@ -1,621 +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. - * - */ - - // - // Original File from r450141 of the Apache ActiveMQ project - // - -// ---------------------------------------------------------------------------- -// OPTIONS -// ---------------------------------------------------------------------------- -options { - STATIC = false; - UNICODE_INPUT = true; - - // some performance optimizations - OPTIMIZE_TOKEN_MANAGER = true; - ERROR_REPORTING = false; -} - -// ---------------------------------------------------------------------------- -// PARSER -// ---------------------------------------------------------------------------- - -PARSER_BEGIN(SelectorParser) -/* - * - * 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.filter.jms.selector; - -import java.io.StringReader; -import java.util.ArrayList; - -import org.apache.qpid.AMQInvalidArgumentException; -import org.apache.qpid.server.filter.ArithmeticExpression; -import org.apache.qpid.server.filter.BooleanExpression; -import org.apache.qpid.server.filter.ComparisonExpression; -import org.apache.qpid.server.filter.ConstantExpression; -import org.apache.qpid.server.filter.Expression; -import org.apache.qpid.server.filter.LogicExpression; -import org.apache.qpid.server.filter.PropertyExpression; -import org.apache.qpid.server.filter.UnaryExpression; - -/** - * JMS Selector Parser generated by JavaCC - * - * Do not edit this .java file directly - it is autogenerated from SelectorParser.jj - */ -public class SelectorParser { - - public SelectorParser() { - this(new StringReader("")); - } - - public BooleanExpression parse(String sql) throws AMQInvalidArgumentException { - this.ReInit(new StringReader(sql)); - - try { - return this.JmsSelector(); - } - catch (Throwable e) { - throw (AMQInvalidArgumentException)new AMQInvalidArgumentException(sql,e); - } - - } - - private BooleanExpression asBooleanExpression(Expression value) throws ParseException { - if (value instanceof BooleanExpression) { - return (BooleanExpression) value; - } - if (value instanceof PropertyExpression) { - return UnaryExpression.createBooleanCast( value ); - } - throw new ParseException("Expression will not result in a boolean value: " + value); - } - - -} - -PARSER_END(SelectorParser) - -// ---------------------------------------------------------------------------- -// Tokens -// ---------------------------------------------------------------------------- - -/* White Space */ -SPECIAL_TOKEN : -{ - " " | "\t" | "\n" | "\r" | "\f" -} - -/* Comments */ -SKIP: -{ - -} - -SKIP: -{ - -} - -/* Reserved Words */ -TOKEN [IGNORE_CASE] : -{ - < NOT : "NOT"> - | < AND : "AND"> - | < OR : "OR"> - | < BETWEEN : "BETWEEN"> - | < LIKE : "LIKE"> - | < ESCAPE : "ESCAPE"> - | < IN : "IN"> - | < IS : "IS"> - | < TRUE : "TRUE" > - | < FALSE : "FALSE" > - | < NULL : "NULL" > - | < XPATH : "XPATH" > - | < XQUERY : "XQUERY" > -} - -/* Literals */ -TOKEN [IGNORE_CASE] : -{ - - < DECIMAL_LITERAL: ["1"-"9"] (["0"-"9"])* (["l","L"])? > - | < HEX_LITERAL: "0" ["x","X"] (["0"-"9","a"-"f","A"-"F"])+ > - | < OCTAL_LITERAL: "0" (["0"-"7"])* > - | < FLOATING_POINT_LITERAL: - (["0"-"9"])+ "." (["0"-"9"])* ()? // matches: 5.5 or 5. or 5.5E10 or 5.E10 - | "." (["0"-"9"])+ ()? // matches: .5 or .5E10 - | (["0"-"9"])+ // matches: 5E10 - > - | < #EXPONENT: "E" (["+","-"])? (["0"-"9"])+ > - | < STRING_LITERAL: "'" ( ("''") | ~["'"] )* "'" > -} - -TOKEN [IGNORE_CASE] : -{ - < ID : ["a"-"z", "_", "$"] (["a"-"z","0"-"9","_", "$"])* > - | < QUOTED_ID : "\"" ( ("\"\"") | ~["\""] )* "\"" > -} - -// ---------------------------------------------------------------------------- -// Grammer -// ---------------------------------------------------------------------------- -BooleanExpression JmsSelector() : -{ - Expression left=null; -} -{ - ( - left = orExpression() - ) - { - return asBooleanExpression(left); - } - -} - -Expression orExpression() : -{ - Expression left; - Expression right; -} -{ - ( - left = andExpression() - ( - right = andExpression() - { - left = LogicExpression.createOR(asBooleanExpression(left), asBooleanExpression(right)); - } - )* - ) - { - return left; - } - -} - - -Expression andExpression() : -{ - Expression left; - Expression right; -} -{ - ( - left = equalityExpression() - ( - right = equalityExpression() - { - left = LogicExpression.createAND(asBooleanExpression(left), asBooleanExpression(right)); - } - )* - ) - { - return left; - } -} - -Expression equalityExpression() : -{ - Expression left; - Expression right; -} -{ - ( - left = comparisonExpression() - ( - - "=" right = comparisonExpression() - { - left = ComparisonExpression.createEqual(left, right); - } - | - "<>" right = comparisonExpression() - { - left = ComparisonExpression.createNotEqual(left, right); - } - | - LOOKAHEAD(2) - - { - left = ComparisonExpression.createIsNull(left); - } - | - - { - left = ComparisonExpression.createIsNotNull(left); - } - )* - ) - { - return left; - } -} - -Expression comparisonExpression() : -{ - Expression left; - Expression right; - Expression low; - Expression high; - String t, u; - boolean not; - ArrayList list; -} -{ - ( - left = addExpression() - ( - - ">" right = addExpression() - { - left = ComparisonExpression.createGreaterThan(left, right); - } - | - ">=" right = addExpression() - { - left = ComparisonExpression.createGreaterThanEqual(left, right); - } - | - "<" right = addExpression() - { - left = ComparisonExpression.createLessThan(left, right); - } - | - "<=" right = addExpression() - { - left = ComparisonExpression.createLessThanEqual(left, right); - } - | - { - u=null; - } - t = stringLitteral() - [ u = stringLitteral() ] - { - left = ComparisonExpression.createLike(left, t, u); - } - | - LOOKAHEAD(2) - { - u=null; - } - t = stringLitteral() [ u = stringLitteral() ] - { - left = ComparisonExpression.createNotLike(left, t, u); - } - | - low = addExpression() high = addExpression() - { - left = ComparisonExpression.createBetween(left, low, high); - } - | - LOOKAHEAD(2) - low = addExpression() high = addExpression() - { - left = ComparisonExpression.createNotBetween(left, low, high); - } - | - - "(" - t = stringLitteral() - { - list = new ArrayList(); - list.add( t ); - } - ( - "," - t = stringLitteral() - { - list.add( t ); - } - - )* - ")" - { - left = ComparisonExpression.createInFilter(left, list); - } - | - LOOKAHEAD(2) - - "(" - t = stringLitteral() - { - list = new ArrayList(); - list.add( t ); - } - ( - "," - t = stringLitteral() - { - list.add( t ); - } - - )* - ")" - { - left = ComparisonExpression.createNotInFilter(left, list); - } - - )* - ) - { - return left; - } -} - -Expression addExpression() : -{ - Expression left; - Expression right; -} -{ - left = multExpr() - ( - LOOKAHEAD( ("+"|"-") multExpr()) - ( - "+" right = multExpr() - { - left = ArithmeticExpression.createPlus(left, right); - } - | - "-" right = multExpr() - { - left = ArithmeticExpression.createMinus(left, right); - } - ) - - )* - { - return left; - } -} - -Expression multExpr() : -{ - Expression left; - Expression right; -} -{ - left = unaryExpr() - ( - "*" right = unaryExpr() - { - left = ArithmeticExpression.createMultiply(left, right); - } - | - "/" right = unaryExpr() - { - left = ArithmeticExpression.createDivide(left, right); - } - | - "%" right = unaryExpr() - { - left = ArithmeticExpression.createMod(left, right); - } - - )* - { - return left; - } -} - - -Expression unaryExpr() : -{ - String s=null; - Expression left=null; -} -{ - ( - LOOKAHEAD( "+" unaryExpr() ) - "+" left=unaryExpr() - | - "-" left=unaryExpr() - { - left = UnaryExpression.createNegate(left); - } - | - left=unaryExpr() - { - left = UnaryExpression.createNOT( asBooleanExpression(left) ); - } - | - s=stringLitteral() - { - left = UnaryExpression.createXPath( s ); - } - | - s=stringLitteral() - { - left = UnaryExpression.createXQuery( s ); - } - | - left = primaryExpr() - ) - { - return left; - } - -} - -Expression primaryExpr() : -{ - Expression left=null; -} -{ - ( - left = literal() - | - left = variable() - | - "(" left = orExpression() ")" - ) - { - return left; - } -} - - - -ConstantExpression literal() : -{ - Token t; - String s; - ConstantExpression left=null; -} -{ - ( - ( - s = stringLitteral() - { - left = new ConstantExpression(s); - } - ) - | - ( - t = - { - left = ConstantExpression.createFromDecimal(t.image); - } - ) - | - ( - t = - { - left = ConstantExpression.createFromHex(t.image); - } - ) - | - ( - t = - { - left = ConstantExpression.createFromOctal(t.image); - } - ) - | - ( - t = - { - left = ConstantExpression.createFloat(t.image); - } - ) - | - ( - - { - left = ConstantExpression.TRUE; - } - ) - | - ( - - { - left = ConstantExpression.FALSE; - } - ) - | - ( - - { - left = ConstantExpression.NULL; - } - ) - ) - { - return left; - } -} - -String stringLitteral() : -{ - Token t; - StringBuffer rc = new StringBuffer(); - boolean first=true; -} -{ - t = - { - // Decode the sting value. - String image = t.image; - for( int i=1; i < image.length()-1; i++ ) { - char c = image.charAt(i); - if( c == '\'' ) - i++; - rc.append(c); - } - return rc.toString(); - } -} - -PropertyExpression variable() : -{ - Token t; - StringBuffer rc = new StringBuffer(); - PropertyExpression left=null; -} -{ - ( - t = - { - left = new PropertyExpression(t.image); - } - | - t = - { - // Decode the sting value. - String image = t.image; - for( int i=1; i < image.length()-1; i++ ) { - char c = image.charAt(i); - if( c == '"' ) - i++; - rc.append(c); - } - return new PropertyExpression(rc.toString()); - } - - - ) - { - return left; - } -} diff --git a/qpid/java/broker/src/main/java/broker.bnd b/qpid/java/broker/src/main/java/broker.bnd index 25b0495a63..fa433848a6 100755 --- a/qpid/java/broker/src/main/java/broker.bnd +++ b/qpid/java/broker/src/main/java/broker.bnd @@ -17,7 +17,7 @@ # under the License. # -ver: 0.15.0 +ver: 0.17.0 Bundle-SymbolicName: qpid-broker Bundle-Version: ${ver} diff --git a/qpid/java/broker/src/main/java/org/apache/log4j/QpidCompositeRollingAppender.java b/qpid/java/broker/src/main/java/org/apache/log4j/QpidCompositeRollingAppender.java index 4426a7aeec..54ca574871 100644 --- a/qpid/java/broker/src/main/java/org/apache/log4j/QpidCompositeRollingAppender.java +++ b/qpid/java/broker/src/main/java/org/apache/log4j/QpidCompositeRollingAppender.java @@ -20,6 +20,11 @@ */ package org.apache.log4j; +import org.apache.log4j.helpers.CountingQuietWriter; +import org.apache.log4j.helpers.LogLog; +import org.apache.log4j.helpers.OptionConverter; +import org.apache.log4j.spi.LoggingEvent; + import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; @@ -33,11 +38,6 @@ import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; import java.util.zip.GZIPOutputStream; -import org.apache.log4j.helpers.CountingQuietWriter; -import org.apache.log4j.helpers.LogLog; -import org.apache.log4j.helpers.OptionConverter; -import org.apache.log4j.spi.LoggingEvent; - /** *

CompositeRollingAppender combines RollingFileAppender and DailyRollingFileAppender
It can function as either * or do both at the same time (making size based rolling files like RollingFileAppender until a data/time boundary is @@ -99,59 +99,38 @@ public class QpidCompositeRollingAppender extends FileAppender private long nextCheck = System.currentTimeMillis() - 1; /** Holds date of last roll over */ - Date now = new Date(); + private Date now = new Date(); - SimpleDateFormat sdf; + private SimpleDateFormat sdf; /** Helper class to determine next rollover time */ - RollingCalendar rc = new RollingCalendar(); + private RollingCalendar rc = new RollingCalendar(); - /** The default maximum file size is 10MB. */ - protected long maxFileSize = 10 * 1024 * 1024; + private long maxFileSize = 10 * 1024 * 1024; - /** There is zero backup files by default. */ - protected int maxSizeRollBackups = 0; - /** How many sized based backups have been made so far */ - protected int curSizeRollBackups = 0; + private int maxSizeRollBackups = 0; + private int curSizeRollBackups = 0; - /** not yet implemented */ - protected int maxTimeRollBackups = -1; - protected int curTimeRollBackups = 0; + private int maxTimeRollBackups = -1; + private int curTimeRollBackups = 0; - /** - * By default newer files have lower numbers. (countDirection < 0) ie. log.1 is most recent, log.5 is the 5th - * backup, etc... countDirection > 0 does the opposite ie. log.1 is the first backup made, log.5 is the 5th backup - * made, etc. For infinite backups use countDirection > 0 to reduce rollOver costs. - */ - protected int countDirection = -1; + private int countDirection = -1; - /** Style of rolling to Use. BY_SIZE (1), BY_DATE(2), BY COMPOSITE(3) */ - protected int rollingStyle = BY_COMPOSITE; - protected boolean rollDate = true; - protected boolean rollSize = true; + private int rollingStyle = BY_COMPOSITE; + private boolean rollDate = true; + private boolean rollSize = true; - /** - * By default file.log is always the current file. Optionally file.log.yyyy-mm-dd for current formated datePattern - * can by the currently logging file (or file.log.curSizeRollBackup or even file.log.yyyy-mm-dd.curSizeRollBackup) - * This will make time based roll overs with a large number of backups much faster -- it won't have to rename all - * the backups! - */ - protected boolean staticLogFileName = true; + private boolean staticLogFileName = true; - /** FileName provided in configuration. Used for rolling properly */ - protected String baseFileName; + private String baseFileName; - /** Do we want to .gz our backup files. */ - protected boolean compress = false; + private boolean compress = false; - /** Do we want to use a second thread when compressing our backup files. */ - protected boolean compressAsync = false; + private boolean compressAsync = false; - /** Do we want to start numbering files at zero. */ - protected boolean zeroBased = false; + private boolean zeroBased = false; - /** Path provided in configuration. Used for moving backup files to */ - protected String backupFilesToPath = null; + private String backupFilesToPath = null; private final ConcurrentLinkedQueue _compress = new ConcurrentLinkedQueue(); private AtomicBoolean _compressing = new AtomicBoolean(false); private static final String COMPRESS_EXTENSION = ".gz"; @@ -219,7 +198,7 @@ public class QpidCompositeRollingAppender extends FileAppender return datePattern; } - /** Returns the value of the maxSizeRollBackups option. */ + /** There is zero backup files by default. */ /** Returns the value of the maxSizeRollBackups option. */ public int getMaxSizeRollBackups() { return maxSizeRollBackups; @@ -311,7 +290,6 @@ public class QpidCompositeRollingAppender extends FileAppender c.setType(i); Date next = new Date(c.getNextCheckMillis(epoch)); String r1 = sdf.format(next); - // LogLog.debug("Type = "+i+", r0 = "+r0+", r1 = "+r1); if ((r0 != null) && (r1 != null) && !r0.equals(r1)) { return i; @@ -379,6 +357,11 @@ public class QpidCompositeRollingAppender extends FileAppender } } + /** + * By default newer files have lower numbers. (countDirection < 0) ie. log.1 is most recent, log.5 is the 5th + * backup, etc... countDirection > 0 does the opposite ie. log.1 is the first backup made, log.5 is the 5th backup + * made, etc. For infinite backups use countDirection > 0 to reduce rollOver costs. + */ public int getCountDirection() { return countDirection; @@ -389,6 +372,7 @@ public class QpidCompositeRollingAppender extends FileAppender countDirection = direction; } + /** Style of rolling to Use. BY_SIZE (1), BY_DATE(2), BY COMPOSITE(3) */ public int getRollingStyle() { return rollingStyle; @@ -420,19 +404,6 @@ public class QpidCompositeRollingAppender extends FileAppender } } - /* - public void setRollingStyle(String style) { - if (style == S_BY_SIZE) { - rollingStyle = BY_SIZE; - } - else if (style == S_BY_DATE) { - rollingStyle = BY_DATE; - } - else if (style == S_BY_COMPOSITE) { - rollingStyle = BY_COMPOSITE; - } - } - */ public boolean getStaticLogFileName() { return staticLogFileName; @@ -484,6 +455,7 @@ public class QpidCompositeRollingAppender extends FileAppender zeroBased = z; } + /** Path provided in configuration. Used for moving backup files to */ public String getBackupFilesToPath() { return backupFilesToPath; @@ -549,7 +521,6 @@ public class QpidCompositeRollingAppender extends FileAppender now.setTime(System.currentTimeMillis()); sdf = new SimpleDateFormat(datePattern); int type = computeCheckPeriod(); - // printPeriodicity(type); rc.setType(type); // next line added as this removes the name check in rollOver nextCheck = rc.getNextCheckMillis(now); @@ -797,7 +768,9 @@ public class QpidCompositeRollingAppender extends FileAppender curSizeRollBackups--; } } - // Map {(maxBackupIndex - 1), ..., 2, 1} to {maxBackupIndex, ..., 3, 2} + /* + map {(maxBackupIndex - 1), ..., 2, 1} to {maxBackupIndex, ..., 3, 2}. + */ for (int i = curSizeRollBackups; i >= 1; i--) { String oldName = (fileName + "." + i); @@ -1074,9 +1047,117 @@ public class QpidCompositeRollingAppender extends FileAppender } } + /** The default maximum file size is 10MB. */ + protected long getMaxFileSize() + { + return maxFileSize; + } + + /** How many sized based backups have been made so far */ + protected int getCurSizeRollBackups() + { + return curSizeRollBackups; + } + + protected void setCurSizeRollBackups(int curSizeRollBackups) + { + this.curSizeRollBackups = curSizeRollBackups; + } + + /** not yet implemented */ + protected int getMaxTimeRollBackups() + { + return maxTimeRollBackups; + } + + protected void setMaxTimeRollBackups(int maxTimeRollBackups) + { + this.maxTimeRollBackups = maxTimeRollBackups; + } + + protected int getCurTimeRollBackups() + { + return curTimeRollBackups; + } + + protected void setCurTimeRollBackups(int curTimeRollBackups) + { + this.curTimeRollBackups = curTimeRollBackups; + } + + protected boolean isRollDate() + { + return rollDate; + } + + protected void setRollDate(boolean rollDate) + { + this.rollDate = rollDate; + } + + protected boolean isRollSize() + { + return rollSize; + } + + protected void setRollSize(boolean rollSize) + { + this.rollSize = rollSize; + } + + /** + * By default file.log is always the current file. Optionally file.log.yyyy-mm-dd for current formated datePattern + * can by the currently logging file (or file.log.curSizeRollBackup or even file.log.yyyy-mm-dd.curSizeRollBackup) + * This will make time based roll overs with a large number of backups much faster -- it won't have to rename all + * the backups! + */ + protected boolean isStaticLogFileName() + { + return staticLogFileName; + } + + /** FileName provided in configuration. Used for rolling properly */ + protected String getBaseFileName() + { + return baseFileName; + } + + protected void setBaseFileName(String baseFileName) + { + this.baseFileName = baseFileName; + } + + /** Do we want to .gz our backup files. */ + protected boolean isCompress() + { + return compress; + } + + protected void setCompress(boolean compress) + { + this.compress = compress; + } + + /** Do we want to use a second thread when compressing our backup files. */ + protected boolean isCompressAsync() + { + return compressAsync; + } + + /** Do we want to start numbering files at zero. */ + protected boolean isZeroBased() + { + return zeroBased; + } + + protected void setBackupFilesToPath(String backupFilesToPath) + { + this.backupFilesToPath = backupFilesToPath; + } + private static class CompressJob { - File _from, _to; + private File _from, _to; CompressJob(File from, File to) { @@ -1095,9 +1176,9 @@ public class QpidCompositeRollingAppender extends FileAppender } } - Compressor compressor = null; + private Compressor compressor = null; - Executor executor; + private Executor executor; private class Compressor implements Runnable { diff --git a/qpid/java/broker/src/main/java/org/apache/log4j/xml/QpidLog4JConfigurator.java b/qpid/java/broker/src/main/java/org/apache/log4j/xml/QpidLog4JConfigurator.java index 1200ba6e0b..dca62f34b4 100644 --- a/qpid/java/broker/src/main/java/org/apache/log4j/xml/QpidLog4JConfigurator.java +++ b/qpid/java/broker/src/main/java/org/apache/log4j/xml/QpidLog4JConfigurator.java @@ -20,22 +20,22 @@ */ package org.apache.log4j.xml; -import java.io.File; -import java.io.IOException; -import java.util.Map; -import java.util.concurrent.locks.ReentrantLock; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; - import org.apache.log4j.Level; import org.apache.log4j.Logger; -import org.apache.qpid.server.logging.management.LoggingManagementMBean; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; +import org.apache.qpid.server.logging.management.LoggingManagementMBean; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import java.io.File; +import java.io.IOException; +import java.util.Map; +import java.util.concurrent.locks.ReentrantLock; + /** * Substitute for the Log4J XMLWatchdog (as used by DOMConfigurator.configureAndWatch) * diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/configuration/Configuration.java b/qpid/java/broker/src/main/java/org/apache/qpid/configuration/Configuration.java deleted file mode 100644 index 0b63c68854..0000000000 --- a/qpid/java/broker/src/main/java/org/apache/qpid/configuration/Configuration.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.configuration; - -import org.apache.commons.cli.CommandLine; -import org.apache.commons.cli.Option; -import org.apache.commons.cli.Options; -import org.apache.commons.cli.ParseException; -import org.apache.commons.cli.PosixParser; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.File; - -public class Configuration -{ - public static final String QPID_HOME = "QPID_HOME"; - - final String QPIDHOME = System.getProperty(QPID_HOME); - - private static Logger _devlog = LoggerFactory.getLogger(Configuration.class); - - public static final String DEFAULT_LOG_CONFIG_FILENAME = "log4j.xml"; - public static final String DEFAULT_CONFIG_FILE = "etc/config.xml"; - - protected final Options _options = new Options(); - protected CommandLine _commandLine; - protected File _configFile; - - - public Configuration() - { - - } - - public void processCommandline(String[] args) throws InitException - { - try - { - _commandLine = new PosixParser().parse(_options, args); - } - catch (ParseException e) - { - throw new InitException("Unable to parse commmandline", e); - } - - final File defaultConfigFile = new File(QPIDHOME, DEFAULT_CONFIG_FILE); - setConfig(new File(_commandLine.getOptionValue("c", defaultConfigFile.getPath()))); - } - - public void setConfig(File file) - { - _configFile = file; - } - - /** - * @param option The option to set. - */ - public void setOption(Option option) - { - _options.addOption(option); - } - - /** - * getOptionValue from the configuration - * @param option variable argument, first string is option to get, second if present is the default value. - * @return the String for the given option or null if not present (if default value not specified) - */ - public String getOptionValue(String... option) - { - if (option.length == 1) - { - return _commandLine.getOptionValue(option[0]); - } - else if (option.length == 2) - { - return _commandLine.getOptionValue(option[0], option[1]); - } - return null; - } - - public void loadConfig(File file) throws InitException - { - setConfig(file); - loadConfig(); - } - - private void loadConfig() throws InitException - { - if (!_configFile.exists()) - { - String error = "File " + _configFile + " could not be found. Check the file exists and is readable."; - - if (QPIDHOME == null) - { - error = error + "\nNote: " + QPID_HOME + " is not set."; - } - - throw new InitException(error, null); - } - else - { - _devlog.debug("Using configuration file " + _configFile.getAbsolutePath()); - } - -// String logConfig = _commandLine.getOptionValue("l"); -// String logWatchConfig = _commandLine.getOptionValue("w", "0"); -// if (logConfig != null) -// { -// File logConfigFile = new File(logConfig); -// configureLogging(logConfigFile, logWatchConfig); -// } -// else -// { -// File configFileDirectory = _configFile.getParentFile(); -// File logConfigFile = new File(configFileDirectory, DEFAULT_LOG_CONFIG_FILENAME); -// configureLogging(logConfigFile, logWatchConfig); -// } - } - - -// private void configureLogging(File logConfigFile, String logWatchConfig) -// { -// int logWatchTime = 0; -// try -// { -// logWatchTime = Integer.parseInt(logWatchConfig); -// } -// catch (NumberFormatException e) -// { -// _devlog.error("Log watch configuration value of " + logWatchConfig + " is invalid. Must be " -// + "a non-negative integer. Using default of zero (no watching configured"); -// } -// -// if (logConfigFile.exists() && logConfigFile.canRead()) -// { -// _devlog.info("Configuring logger using configuration file " + logConfigFile.getAbsolutePath()); -// if (logWatchTime > 0) -// { -// _devlog.info("log file " + logConfigFile.getAbsolutePath() + " will be checked for changes every " -// + logWatchTime + " seconds"); -// // log4j expects the watch interval in milliseconds -// DOMConfigurator.configureAndWatch(logConfigFile.getAbsolutePath(), logWatchTime * 1000); -// } -// else -// { -// DOMConfigurator.configure(logConfigFile.getAbsolutePath()); -// } -// } -// else -// { -// System.err.println("Logging configuration error: unable to read file " + logConfigFile.getAbsolutePath()); -// System.err.println("Using basic log4j configuration"); -// BasicConfigurator.configure(); -// } -// } - - public File getConfigFile() - { - return _configFile; - } - - - public static class InitException extends Exception - { - InitException(String msg, Throwable cause) - { - super(msg, cause); - } - } -} \ No newline at end of file diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/qmf/ManagementExchange.java b/qpid/java/broker/src/main/java/org/apache/qpid/qmf/ManagementExchange.java index b898e85aa2..2d6f7e0946 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/qmf/ManagementExchange.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/qmf/ManagementExchange.java @@ -35,7 +35,6 @@ import org.apache.qpid.server.exchange.topic.TopicExchangeResult; import org.apache.qpid.server.exchange.topic.TopicMatcherResult; import org.apache.qpid.server.exchange.topic.TopicNormalizer; import org.apache.qpid.server.exchange.topic.TopicParser; -import org.apache.qpid.server.message.AMQMessageHeader; import org.apache.qpid.server.message.InboundMessage; import org.apache.qpid.server.message.ServerMessage; import org.apache.qpid.server.queue.AMQQueue; @@ -50,7 +49,6 @@ import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; -import java.util.TimerTask; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; @@ -412,6 +410,11 @@ public class ManagementExchange implements Exchange, QMFService.Listener return queues; } + public boolean isBound(String bindingKey, Map arguments, AMQQueue queue) + { + return false; //TODO + } + public boolean isBound(AMQShortString routingKey, FieldTable arguments, AMQQueue queue) { return false; //To change body of implemented methods use File | Settings | File Templates. diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFBrokerRequestCommand.java b/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFBrokerRequestCommand.java index 709b59588d..69284abc48 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFBrokerRequestCommand.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFBrokerRequestCommand.java @@ -22,17 +22,14 @@ package org.apache.qpid.qmf; import org.apache.log4j.Logger; -import org.apache.qpid.transport.codec.BBDecoder; -import org.apache.qpid.transport.codec.BBEncoder; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.message.MessageTransferMessage; -import org.apache.qpid.server.virtualhost.VirtualHost; + +import org.apache.qpid.AMQException; import org.apache.qpid.server.exchange.Exchange; +import org.apache.qpid.server.message.ServerMessage; import org.apache.qpid.server.queue.BaseQueue; -import org.apache.qpid.AMQException; -import org.apache.qpid.management.common.mbeans.ManagedConnection; +import org.apache.qpid.server.virtualhost.VirtualHost; +import org.apache.qpid.transport.codec.BBDecoder; -import java.util.ArrayList; import java.util.List; public class QMFBrokerRequestCommand extends QMFCommand diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFBrokerResponseCommand.java b/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFBrokerResponseCommand.java index ac01c47fe8..34b2a851dc 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFBrokerResponseCommand.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFBrokerResponseCommand.java @@ -22,7 +22,6 @@ package org.apache.qpid.qmf; import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.server.message.ServerMessage; import org.apache.qpid.transport.codec.BBEncoder; public class QMFBrokerResponseCommand extends QMFCommand diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFClass.java b/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFClass.java index 3408ff09f4..7d566567a1 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFClass.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFClass.java @@ -21,12 +21,10 @@ package org.apache.qpid.qmf; -import org.apache.qpid.server.configuration.ConfiguredObject; - import java.util.Collection; -import java.util.Map; -import java.util.List; import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; abstract public class QMFClass { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFClassIndicationCommand.java b/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFClassIndicationCommand.java index a956a9bd70..613e1e5978 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFClassIndicationCommand.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFClassIndicationCommand.java @@ -21,8 +21,6 @@ package org.apache.qpid.qmf; -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.server.message.ServerMessage; import org.apache.qpid.transport.codec.BBEncoder; public class QMFClassIndicationCommand extends QMFCommand diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFClassQueryCommand.java b/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFClassQueryCommand.java index 64edc2f294..5676bb7306 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFClassQueryCommand.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFClassQueryCommand.java @@ -22,15 +22,15 @@ package org.apache.qpid.qmf; import org.apache.log4j.Logger; -import org.apache.qpid.transport.codec.BBDecoder; -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.server.message.ServerMessage; + +import org.apache.qpid.AMQException; import org.apache.qpid.server.exchange.Exchange; +import org.apache.qpid.server.message.ServerMessage; import org.apache.qpid.server.queue.BaseQueue; import org.apache.qpid.server.registry.IApplicationRegistry; -import org.apache.qpid.AMQException; +import org.apache.qpid.server.virtualhost.VirtualHost; +import org.apache.qpid.transport.codec.BBDecoder; -import java.util.ArrayList; import java.util.Collection; import java.util.List; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFCommandCompletionCommand.java b/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFCommandCompletionCommand.java index 9a25201d4c..397ad4090e 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFCommandCompletionCommand.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFCommandCompletionCommand.java @@ -21,8 +21,6 @@ package org.apache.qpid.qmf; -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.server.message.ServerMessage; import org.apache.qpid.transport.codec.BBEncoder; public class QMFCommandCompletionCommand extends QMFCommand diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFEventCommand.java b/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFEventCommand.java index d70c12db19..833ccfbca4 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFEventCommand.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFEventCommand.java @@ -20,8 +20,6 @@ */ package org.apache.qpid.qmf; -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.server.message.ServerMessage; import org.apache.qpid.transport.codec.BBEncoder; public abstract class QMFEventCommand extends QMFCommand diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFGetQueryCommand.java b/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFGetQueryCommand.java index c11e1a9b27..b1f958d4ba 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFGetQueryCommand.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFGetQueryCommand.java @@ -22,15 +22,21 @@ package org.apache.qpid.qmf; import org.apache.log4j.Logger; -import org.apache.qpid.transport.codec.BBDecoder; -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.server.message.ServerMessage; + +import org.apache.qpid.AMQException; import org.apache.qpid.server.exchange.Exchange; +import org.apache.qpid.server.message.ServerMessage; import org.apache.qpid.server.queue.BaseQueue; import org.apache.qpid.server.registry.IApplicationRegistry; -import org.apache.qpid.AMQException; +import org.apache.qpid.server.virtualhost.VirtualHost; +import org.apache.qpid.transport.codec.BBDecoder; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.UUID; public class QMFGetQueryCommand extends QMFCommand { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFMessage.java b/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFMessage.java index 3248a5aae0..97e74bed89 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFMessage.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFMessage.java @@ -22,9 +22,13 @@ package org.apache.qpid.qmf; import org.apache.commons.lang.NotImplementedException; + import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.server.configuration.SessionConfig; -import org.apache.qpid.server.message.*; +import org.apache.qpid.server.message.AMQMessageHeader; +import org.apache.qpid.server.message.InboundMessage; +import org.apache.qpid.server.message.MessageReference; +import org.apache.qpid.server.message.ServerMessage; import org.apache.qpid.server.store.StoredMessage; import org.apache.qpid.transport.codec.BBEncoder; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFMethod.java b/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFMethod.java index 63e8fa6a1e..1d1cd24724 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFMethod.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFMethod.java @@ -21,12 +21,12 @@ package org.apache.qpid.qmf; -import org.apache.qpid.transport.codec.Encoder; import org.apache.qpid.transport.codec.BBDecoder; +import org.apache.qpid.transport.codec.Encoder; +import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; -import java.util.ArrayList; public abstract class QMFMethod { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFMethodRequestCommand.java b/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFMethodRequestCommand.java index 4001a2a321..1a4ce228b5 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFMethodRequestCommand.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFMethodRequestCommand.java @@ -21,16 +21,16 @@ package org.apache.qpid.qmf; import org.apache.log4j.Logger; -import org.apache.qpid.transport.codec.BBDecoder; -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.server.message.ServerMessage; + +import org.apache.qpid.AMQException; import org.apache.qpid.server.exchange.Exchange; +import org.apache.qpid.server.message.ServerMessage; import org.apache.qpid.server.queue.BaseQueue; -import org.apache.qpid.AMQException; +import org.apache.qpid.server.virtualhost.VirtualHost; +import org.apache.qpid.transport.codec.BBDecoder; import java.util.List; import java.util.UUID; -import java.util.ArrayList; public class QMFMethodRequestCommand extends QMFCommand { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFPackage.java b/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFPackage.java index 681e64b799..63b43475aa 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFPackage.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFPackage.java @@ -22,8 +22,8 @@ package org.apache.qpid.qmf; import java.util.Collection; -import java.util.Map; import java.util.HashMap; +import java.util.Map; public class QMFPackage { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFPackageIndicationCommand.java b/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFPackageIndicationCommand.java index 7053b80655..9c8fa1e2c6 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFPackageIndicationCommand.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFPackageIndicationCommand.java @@ -21,8 +21,6 @@ package org.apache.qpid.qmf; -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.server.message.ServerMessage; import org.apache.qpid.transport.codec.BBEncoder; public class QMFPackageIndicationCommand extends QMFCommand diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFPackageQueryCommand.java b/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFPackageQueryCommand.java index 9cacbafcc1..c74c7da252 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFPackageQueryCommand.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFPackageQueryCommand.java @@ -22,15 +22,15 @@ package org.apache.qpid.qmf; import org.apache.log4j.Logger; -import org.apache.qpid.transport.codec.BBDecoder; -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.server.message.ServerMessage; + +import org.apache.qpid.AMQException; import org.apache.qpid.server.exchange.Exchange; +import org.apache.qpid.server.message.ServerMessage; import org.apache.qpid.server.queue.BaseQueue; import org.apache.qpid.server.registry.IApplicationRegistry; -import org.apache.qpid.AMQException; +import org.apache.qpid.server.virtualhost.VirtualHost; +import org.apache.qpid.transport.codec.BBDecoder; -import java.util.ArrayList; import java.util.Collection; import java.util.List; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFProperty.java b/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFProperty.java index 5748722afe..5314466e2a 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFProperty.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFProperty.java @@ -23,9 +23,8 @@ package org.apache.qpid.qmf; import org.apache.qpid.transport.codec.Encoder; -import java.util.Map; -import java.util.HashMap; import java.util.LinkedHashMap; +import java.util.Map; public class QMFProperty { @@ -68,8 +67,6 @@ public class QMFProperty public void setQMFClass(QMFClass qmfClass) { - /* _map.put(REF_CLASS, qmfClass.getName()); - _map.put(REF_PACKAGE, qmfClass.getPackage().getName());*/ } public void setReferencedClass(String refClass) diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFSchemaRequestCommand.java b/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFSchemaRequestCommand.java index a1260ed9e6..57c67fa7f6 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFSchemaRequestCommand.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFSchemaRequestCommand.java @@ -22,16 +22,15 @@ package org.apache.qpid.qmf; import org.apache.log4j.Logger; -import org.apache.qpid.transport.codec.BBDecoder; -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.registry.IApplicationRegistry; + +import org.apache.qpid.AMQException; import org.apache.qpid.server.exchange.Exchange; +import org.apache.qpid.server.message.ServerMessage; import org.apache.qpid.server.queue.BaseQueue; -import org.apache.qpid.AMQException; +import org.apache.qpid.server.registry.IApplicationRegistry; +import org.apache.qpid.server.virtualhost.VirtualHost; +import org.apache.qpid.transport.codec.BBDecoder; -import java.util.Collection; -import java.util.ArrayList; import java.util.List; public class QMFSchemaRequestCommand extends QMFCommand diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFSchemaResponseCommand.java b/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFSchemaResponseCommand.java index fea2430130..4bd0e41989 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFSchemaResponseCommand.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFSchemaResponseCommand.java @@ -21,8 +21,6 @@ package org.apache.qpid.qmf; -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.server.message.ServerMessage; import org.apache.qpid.transport.codec.BBEncoder; import java.util.Collection; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFService.java b/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFService.java index 27345f0a88..900b722886 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFService.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/qmf/QMFService.java @@ -658,6 +658,11 @@ public class QMFService implements ConfigStore.ConfigEventListener, Closeable return _obj.getStagingThreshold(); } + public Boolean getMgmtPublish() + { + return true; + } + public Integer getMgmtPubInterval() { return _obj.getManagementPublishInterval(); @@ -678,6 +683,204 @@ public class QMFService implements ConfigStore.ConfigEventListener, Closeable return (System.currentTimeMillis() - _obj.getCreateTime()) * 1000000L; } + public Long getQueueCount() + { + // TODO + return 0L; + } + + public Long getMsgTotalEnqueues() + { + // TODO + return 0L; + } + + public Long getMsgTotalDequeues() + { + // TODO + return 0L; + } + + public Long getByteTotalEnqueues() + { + // TODO + return 0L; + } + + public Long getByteTotalDequeues() + { + // TODO + return 0L; + } + + public Long getMsgDepth() + { + // TODO + return 0L; + } + + public Long getByteDepth() + { + // TODO + return 0L; + } + + public Long getMsgPersistEnqueues() + { + // TODO + return 0L; + } + + public Long getMsgPersistDequeues() + { + // TODO + return 0L; + } + + public Long getBytePersistEnqueues() + { + // TODO + return 0L; + } + + public Long getBytePersistDequeues() + { + // TODO + return 0L; + } + + public Long getMsgTxnEnqueues() + { + // TODO + return 0L; + } + + public Long getMsgTxnDequeues() + { + // TODO + return 0L; + } + + public Long getByteTxnEnqueues() + { + // TODO + return 0L; + } + + public Long getByteTxnDequeues() + { + // TODO + return 0L; + } + + public Long getMsgFtdEnqueues() + { + // TODO + return 0L; + } + + public Long getMsgFtdDequeues() + { + // TODO + return 0L; + } + + public Long getByteFtdEnqueues() + { + // TODO + return 0L; + } + + public Long getByteFtdDequeues() + { + // TODO + return 0L; + } + + public Long getMsgFtdDepth() + { + // TODO + return 0L; + } + + public Long getByteFtdDepth() + { + // TODO + return 0L; + } + + public Long getReleases() + { + // TODO + return 0L; + } + + public Long getAcquires() + { + // TODO + return 0L; + } + + public Long getDiscardsNoRoute() + { + // TODO + return 0L; + } + + public Long getDiscardsTtl() + { + // TODO + return 0L; + } + + public Long getDiscardsRing() + { + // TODO + return 0L; + } + + public Long getDiscardsLvq() + { + // TODO + return 0L; + } + + public Long getDiscardsOverflow() + { + // TODO + return 0L; + } + + public Long getDiscardsSubscriber() + { + // TODO + return 0L; + } + + public Long getDiscardsPurge() + { + // TODO + return 0L; + } + + public Long getReroutes() + { + // TODO + return 0L; + } + + public Long getAbandoned() + { + // TODO + return 0L; + } + + public Long getAbandonedViaAlt() + { + // TODO + return 0L; + } + public BrokerSchema.BrokerClass.EchoMethodResponseCommand echo(final BrokerSchema.BrokerClass.EchoMethodResponseCommandFactory factory, final Long sequence, final String body) @@ -1064,6 +1267,96 @@ public class QMFService implements ConfigStore.ConfigEventListener, Closeable return _obj.getPersistentByteDequeues(); } + public Long getMsgFtdEnqueues() + { + // TODO + return 0L; + } + + public Long getMsgFtdDequeues() + { + // TODO + return 0L; + } + + public Long getByteFtdEnqueues() + { + // TODO + return 0L; + } + + public Long getByteFtdDequeues() + { + // TODO + return 0L; + } + + public Long getMsgFtdDepth() + { + // TODO + return 0L; + } + + public Long getByteFtdDepth() + { + // TODO + return 0L; + } + + public Long getReleases() + { + // TODO + return 0L; + } + + public Long getAcquires() + { + // TODO + return 0L; + } + + public Long getDiscardsTtl() + { + // TODO + return 0L; + } + + public Long getDiscardsRing() + { + // TODO + return 0L; + } + + public Long getDiscardsLvq() + { + // TODO + return 0L; + } + + public Long getDiscardsOverflow() + { + // TODO + return 0L; + } + + public Long getDiscardsSubscriber() + { + // TODO + return 0L; + } + + public Long getDiscardsPurge() + { + // TODO + return 0L; + } + + public Long getReroutes() + { + // TODO + return 0L; + } + public Long getConsumerCount() { return (long) _obj.getConsumerCount(); diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/AMQBrokerManagerMBean.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/AMQBrokerManagerMBean.java index 01a0d9900d..265aa7714e 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/AMQBrokerManagerMBean.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/AMQBrokerManagerMBean.java @@ -18,16 +18,6 @@ */ package org.apache.qpid.server; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.management.JMException; -import javax.management.MBeanException; -import javax.management.MalformedObjectNameException; -import javax.management.ObjectName; - import org.apache.qpid.AMQException; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.framing.FieldTable; @@ -39,6 +29,8 @@ import org.apache.qpid.server.exchange.Exchange; import org.apache.qpid.server.exchange.ExchangeFactory; import org.apache.qpid.server.exchange.ExchangeRegistry; import org.apache.qpid.server.exchange.ExchangeType; +import org.apache.qpid.server.logging.actors.CurrentActor; +import org.apache.qpid.server.logging.actors.ManagementActor; import org.apache.qpid.server.management.AMQManagedObject; import org.apache.qpid.server.management.ManagedObject; import org.apache.qpid.server.queue.AMQQueue; @@ -48,8 +40,15 @@ import org.apache.qpid.server.queue.QueueRegistry; import org.apache.qpid.server.store.DurableConfigurationStore; import org.apache.qpid.server.virtualhost.VirtualHost; import org.apache.qpid.server.virtualhost.VirtualHostImpl; -import org.apache.qpid.server.logging.actors.CurrentActor; -import org.apache.qpid.server.logging.actors.ManagementActor; + +import javax.management.JMException; +import javax.management.MBeanException; +import javax.management.MalformedObjectNameException; +import javax.management.ObjectName; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; /** * This MBean implements the broker management interface and exposes the @@ -169,7 +168,7 @@ public class AMQBrokerManagerMBean extends AMQManagedObject implements ManagedBr */ public void createNewExchange(String exchangeName, String type, boolean durable) throws JMException, MBeanException { - CurrentActor.set(new ManagementActor(_logActor.getRootMessageLogger())); + CurrentActor.set(new ManagementActor(getLogActor().getRootMessageLogger())); try { synchronized (_exchangeRegistry) @@ -213,10 +212,10 @@ public class AMQBrokerManagerMBean extends AMQManagedObject implements ManagedBr { // TODO // Check if the exchange is in use. - // boolean inUse = false; + // Check if there are queue-bindings with the exchange and unregister // when there are no bindings. - CurrentActor.set(new ManagementActor(_logActor.getRootMessageLogger())); + CurrentActor.set(new ManagementActor(getLogActor().getRootMessageLogger())); try { _exchangeRegistry.unregisterExchange(new AMQShortString(exchangeName), false); @@ -256,7 +255,7 @@ public class AMQBrokerManagerMBean extends AMQManagedObject implements ManagedBr throw new JMException("The queue \"" + queueName + "\" already exists."); } - CurrentActor.set(new ManagementActor(_logActor.getRootMessageLogger())); + CurrentActor.set(new ManagementActor(getLogActor().getRootMessageLogger())); try { AMQShortString ownerShortString = null; @@ -312,7 +311,7 @@ public class AMQBrokerManagerMBean extends AMQManagedObject implements ManagedBr throw new JMException("The Queue " + queueName + " is not a registered queue."); } - CurrentActor.set(new ManagementActor(_logActor.getRootMessageLogger())); + CurrentActor.set(new ManagementActor(getLogActor().getRootMessageLogger())); try { queue.delete(); diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/AMQChannel.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/AMQChannel.java index c0ecbb3630..2d2bc5fad7 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/AMQChannel.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/AMQChannel.java @@ -20,8 +20,23 @@ */ package org.apache.qpid.server; -import org.apache.log4j.Logger; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; +import java.util.UUID; +import java.util.concurrent.ConcurrentSkipListSet; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicLong; +import org.apache.log4j.Logger; import org.apache.qpid.AMQException; import org.apache.qpid.AMQSecurityException; import org.apache.qpid.framing.AMQMethodBody; @@ -57,10 +72,10 @@ import org.apache.qpid.server.message.MessageMetaData; import org.apache.qpid.server.message.MessageReference; import org.apache.qpid.server.message.ServerMessage; import org.apache.qpid.server.output.ProtocolOutputConverter; +import org.apache.qpid.server.protocol.AMQConnectionModel; import org.apache.qpid.server.protocol.AMQProtocolEngine; import org.apache.qpid.server.protocol.AMQProtocolSession; import org.apache.qpid.server.protocol.AMQSessionModel; -import org.apache.qpid.server.protocol.AMQConnectionModel; import org.apache.qpid.server.queue.AMQQueue; import org.apache.qpid.server.queue.BaseQueue; import org.apache.qpid.server.queue.InboundMessageAdapter; @@ -75,18 +90,11 @@ import org.apache.qpid.server.subscription.Subscription; import org.apache.qpid.server.subscription.SubscriptionFactoryImpl; import org.apache.qpid.server.subscription.SubscriptionImpl; import org.apache.qpid.server.txn.AsyncAutoCommitTransaction; -import org.apache.qpid.server.txn.AutoCommitTransaction; import org.apache.qpid.server.txn.LocalTransaction; import org.apache.qpid.server.txn.ServerTransaction; import org.apache.qpid.server.virtualhost.VirtualHost; import org.apache.qpid.transport.TransportException; -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicLong; - public class AMQChannel implements SessionConfig, AMQSessionModel, AsyncAutoCommitTransaction.FutureRecorder { public static final int DEFAULT_PREFETCH = 4096; @@ -122,7 +130,7 @@ public class AMQChannel implements SessionConfig, AMQSessionModel, AsyncAutoComm private IncomingMessage _currentMessage; /** Maps from consumer tag to subscription instance. Allows us to unsubscribe from a queue. */ - protected final Map _tag2SubscriptionMap = new HashMap(); + private final Map _tag2SubscriptionMap = new HashMap(); private final MessageStore _messageStore; @@ -148,7 +156,7 @@ public class AMQChannel implements SessionConfig, AMQSessionModel, AsyncAutoComm private final AMQProtocolSession _session; private AtomicBoolean _closing = new AtomicBoolean(false); - private final ConcurrentMap _blockingQueues = new ConcurrentHashMap(); + private final Set _blockingQueues = new ConcurrentSkipListSet(); private final AtomicBoolean _blocking = new AtomicBoolean(false); @@ -267,7 +275,7 @@ public class AMQChannel implements SessionConfig, AMQSessionModel, AsyncAutoComm { throw new AMQSecurityException("Permission denied: " + e.getName()); } - _currentMessage = new IncomingMessage(info); + _currentMessage = new IncomingMessage(info, getProtocolSession().getReference()); _currentMessage.setExchange(e); } @@ -289,26 +297,9 @@ public class AMQChannel implements SessionConfig, AMQSessionModel, AsyncAutoComm _currentMessage.setExpiration(); + _currentMessage.headersReceived(getProtocolSession().getLastReceivedTime()); - MessageMetaData mmd = _currentMessage.headersReceived(getProtocolSession().getLastReceivedTime()); - final StoredMessage handle = _messageStore.addMessage(mmd); - _currentMessage.setStoredMessage(handle); - - routeCurrentMessage(); - - - _transaction.addPostTransactionAction(new ServerTransaction.Action() - { - - public void postCommit() - { - } - - public void onRollback() - { - handle.remove(); - } - }); + _currentMessage.route(); deliverCurrentMessageIfComplete(); } @@ -340,17 +331,41 @@ public class AMQChannel implements SessionConfig, AMQSessionModel, AsyncAutoComm { _actor.message(ExchangeMessages.DISCARDMSG(_currentMessage.getExchange().asString(), _currentMessage.getRoutingKey())); } - } else { + final StoredMessage handle = _messageStore.addMessage(_currentMessage.getMessageMetaData()); + _currentMessage.setStoredMessage(handle); + int bodyCount = _currentMessage.getBodyCount(); + if(bodyCount > 0) + { + long bodyLengthReceived = 0; + for(int i = 0 ; i < bodyCount ; i++) + { + ContentChunk contentChunk = _currentMessage.getContentChunk(i); + handle.addContent((int)bodyLengthReceived, ByteBuffer.wrap(contentChunk.getData())); + bodyLengthReceived += contentChunk.getSize(); + } + } + + _transaction.addPostTransactionAction(new ServerTransaction.Action() + { + public void postCommit() + { + } + + public void onRollback() + { + handle.remove(); + } + }); + _transaction.enqueue(destinationQueues, _currentMessage, new MessageDeliveryAction(_currentMessage, destinationQueues), getProtocolSession().getLastReceivedTime()); incrementOutstandingTxnsIfNecessary(); - updateTransactionalActivity(); + updateTransactionalActivity(); + _currentMessage.getStoredMessage().flushToStore(); } } - _currentMessage.getStoredMessage().flushToStore(); - } finally { @@ -377,9 +392,6 @@ public class AMQChannel implements SessionConfig, AMQSessionModel, AsyncAutoComm try { - - // returns true iff the message was delivered (i.e. if all data was - // received final ContentChunk contentChunk = _session.getMethodRegistry().getProtocolVersionMethodConverter().convertToContentChunk(contentBody); @@ -403,11 +415,6 @@ public class AMQChannel implements SessionConfig, AMQSessionModel, AsyncAutoComm } } - protected void routeCurrentMessage() throws AMQException - { - _currentMessage.route(); - } - public long getNextDeliveryTag() { return ++_deliveryTag; @@ -777,20 +784,6 @@ public class AMQChannel implements SessionConfig, AMQSessionModel, AsyncAutoComm AMQQueue queue = message.getQueue(); - // Our Java Client will always suspend the channel when resending! - // If the client has requested the messages be resent then it is - // their responsibility to ensure that thay are capable of receiving them - // i.e. The channel hasn't been server side suspended. - // if (isSuspended()) - // { - // _logger.info("Channel is suspended so requeuing"); - // //move this message to requeue - // msgToRequeue.add(message); - // } - // else - // { - // release to allow it to be delivered - // Without any details from the client about what has been processed we have to mark // all messages in the unacked map as redelivered. message.setRedelivered(); @@ -1116,7 +1109,7 @@ public class AMQChannel implements SessionConfig, AMQSessionModel, AsyncAutoComm AMQMessage message = new AMQMessage(incomingMessage.getStoredMessage()); message.setExpiration(incomingMessage.getExpiration()); - message.setClientIdentifier(_session); + message.setConnectionIdentifier(_session.getReference()); return message; } @@ -1370,7 +1363,7 @@ public class AMQChannel implements SessionConfig, AMQSessionModel, AsyncAutoComm public void block(AMQQueue queue) { - if(_blockingQueues.putIfAbsent(queue, Boolean.TRUE) == null) + if(_blockingQueues.add(queue)) { if(_blocking.compareAndSet(false,true)) @@ -1394,6 +1387,16 @@ public class AMQChannel implements SessionConfig, AMQSessionModel, AsyncAutoComm } } + public boolean onSameConnection(InboundMessage inbound) + { + if(inbound instanceof IncomingMessage) + { + IncomingMessage incoming = (IncomingMessage) inbound; + return getProtocolSession().getReference() == incoming.getConnectionReference(); + } + return false; + } + private void flow(boolean flow) { MethodRegistry methodRegistry = _session.getMethodRegistry(); @@ -1623,4 +1626,8 @@ public class AMQChannel implements SessionConfig, AMQSessionModel, AsyncAutoComm } } + public int compareTo(AMQSessionModel session) + { + return getId().toString().compareTo(session.getID().toString()); + } } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/Broker.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/Broker.java index e3d8747d72..da26fe1fc4 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/Broker.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/Broker.java @@ -20,24 +20,10 @@ */ package org.apache.qpid.server; -import static org.apache.qpid.transport.ConnectionSettings.WILDCARD_ADDRESS; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.util.EnumSet; -import java.util.HashSet; -import java.util.List; -import java.util.Properties; -import java.util.Set; -import java.util.logging.*; - -import javax.net.ssl.SSLContext; - +import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.xml.QpidLog4JConfigurator; + import org.apache.qpid.server.configuration.ServerConfiguration; import org.apache.qpid.server.configuration.ServerNetworkTransportConfiguration; import org.apache.qpid.server.configuration.management.ConfigurationManagementMBean; @@ -58,10 +44,33 @@ import org.apache.qpid.transport.NetworkTransportConfiguration; import org.apache.qpid.transport.network.IncomingNetworkTransport; import org.apache.qpid.transport.network.Transport; +import static org.apache.qpid.transport.ConnectionSettings.WILDCARD_ADDRESS; + +import javax.net.ssl.SSLContext; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.util.EnumSet; +import java.util.HashSet; +import java.util.List; +import java.util.Properties; +import java.util.Set; +import java.util.logging.ConsoleHandler; +import java.util.logging.FileHandler; +import java.util.logging.Formatter; +import java.util.logging.Handler; +import java.util.logging.Level; +import java.util.logging.LogRecord; + public class Broker { + private static final Logger LOGGER = Logger.getLogger(Broker.class); + private static final int IPV4_ADDRESS_LENGTH = 4; private static final char IPV4_LITERAL_SEPARATOR = '.'; + private volatile Thread _shutdownHookThread; private java.util.logging.Logger FRAME_LOGGER; private java.util.logging.Logger RAW_LOGGER; @@ -79,7 +88,14 @@ public class Broker public void shutdown() { - ApplicationRegistry.remove(); + try + { + removeShutdownHook(); + } + finally + { + ApplicationRegistry.remove(); + } } public void startup() throws Exception @@ -93,6 +109,7 @@ public class Broker { CurrentActor.set(new BrokerActor(new SystemOutMessageLogger())); startupImpl(options); + addShutdownHook(); } finally { @@ -185,32 +202,37 @@ public class Broker bindAddr = serverConfig.getBind(); } - InetAddress bindAddress = null; + InetAddress bindAddress; if (bindAddr.equals(WILDCARD_ADDRESS)) { - bindAddress = new InetSocketAddress(0).getAddress(); + bindAddress = null; } else { - bindAddress = InetAddress.getByAddress(parseIP(bindAddr)); + bindAddress = InetAddress.getByName(bindAddr); } - String hostName = bindAddress.getCanonicalHostName(); + + final AmqpProtocolVersion defaultSupportedProtocolReply = serverConfig.getDefaultSupportedProtocolReply(); if (!serverConfig.getSSLOnly()) { for(int port : ports) { + final InetSocketAddress inetSocketAddress = new InetSocketAddress(bindAddress, port); + final Set supported = - getSupportedVersions(port, exclude_0_10, exclude_0_9_1, exclude_0_9, exclude_0_8); + getSupportedVersions(port, exclude_0_10, exclude_0_9_1, exclude_0_9, exclude_0_8, serverConfig); + final NetworkTransportConfiguration settings = - new ServerNetworkTransportConfiguration(serverConfig, port, bindAddress.getHostName(), Transport.TCP); + new ServerNetworkTransportConfiguration(serverConfig, inetSocketAddress, Transport.TCP); final IncomingNetworkTransport transport = Transport.getIncomingTransportInstance(); final MultiVersionProtocolEngineFactory protocolEngineFactory = - new MultiVersionProtocolEngineFactory(hostName, supported); + new MultiVersionProtocolEngineFactory(supported, defaultSupportedProtocolReply); transport.accept(settings, protocolEngineFactory, null); - ApplicationRegistry.getInstance().addAcceptor(new InetSocketAddress(bindAddress, port), + + ApplicationRegistry.getInstance().addAcceptor(inetSocketAddress, new QpidAcceptor(transport,"TCP")); CurrentActor.get().message(BrokerMessages.LISTENING("TCP", port)); } @@ -220,22 +242,25 @@ public class Broker { final String keystorePath = serverConfig.getConnectorKeyStorePath(); final String keystorePassword = serverConfig.getConnectorKeyStorePassword(); - final String certType = serverConfig.getConnectorCertType(); - final SSLContext sslContext = SSLContextFactory.buildServerContext(keystorePath, keystorePassword, certType); + final String keyManagerFactoryAlgorithm = serverConfig.getConnectorKeyManagerFactoryAlgorithm(); + final SSLContext sslContext = SSLContextFactory.buildServerContext(keystorePath, keystorePassword, keyManagerFactoryAlgorithm); for(int sslPort : sslPorts) { + final InetSocketAddress inetSocketAddress = new InetSocketAddress(bindAddress, sslPort); + final Set supported = - getSupportedVersions(sslPort, exclude_0_10, exclude_0_9_1, exclude_0_9, exclude_0_8); + getSupportedVersions(sslPort, exclude_0_10, exclude_0_9_1, exclude_0_9, exclude_0_8, serverConfig); final NetworkTransportConfiguration settings = - new ServerNetworkTransportConfiguration(serverConfig, sslPort, bindAddress.getHostName(), Transport.TCP); + new ServerNetworkTransportConfiguration(serverConfig, inetSocketAddress, Transport.TCP); final IncomingNetworkTransport transport = Transport.getIncomingTransportInstance(); final MultiVersionProtocolEngineFactory protocolEngineFactory = - new MultiVersionProtocolEngineFactory(hostName, supported); + new MultiVersionProtocolEngineFactory(supported, defaultSupportedProtocolReply); transport.accept(settings, protocolEngineFactory, sslContext); - ApplicationRegistry.getInstance().addAcceptor(new InetSocketAddress(bindAddress, sslPort), + + ApplicationRegistry.getInstance().addAcceptor(inetSocketAddress, new QpidAcceptor(transport,"TCP")); CurrentActor.get().message(BrokerMessages.LISTENING("TCP/SSL", sslPort)); } @@ -252,23 +277,24 @@ public class Broker private static Set getSupportedVersions(final int port, final Set exclude_0_10, final Set exclude_0_9_1, final Set exclude_0_9, - final Set exclude_0_8) + final Set exclude_0_8, + final ServerConfiguration serverConfig) { final EnumSet supported = EnumSet.allOf(AmqpProtocolVersion.class); - if(exclude_0_10.contains(port)) + if(exclude_0_10.contains(port) || !serverConfig.isAmqp010enabled()) { supported.remove(AmqpProtocolVersion.v0_10); } - if(exclude_0_9_1.contains(port)) + if(exclude_0_9_1.contains(port) || !serverConfig.isAmqp091enabled()) { supported.remove(AmqpProtocolVersion.v0_9_1); } - if(exclude_0_9.contains(port)) + if(exclude_0_9.contains(port) || !serverConfig.isAmqp09enabled()) { supported.remove(AmqpProtocolVersion.v0_9); } - if(exclude_0_8.contains(port)) + if(exclude_0_8.contains(port) || !serverConfig.isAmqp08enabled()) { supported.remove(AmqpProtocolVersion.v0_8); } @@ -354,34 +380,6 @@ public class Broker } } - private byte[] parseIP(String address) throws Exception - { - char[] literalBuffer = address.toCharArray(); - int byteCount = 0; - int currByte = 0; - byte[] ip = new byte[IPV4_ADDRESS_LENGTH]; - for (int i = 0; i < literalBuffer.length; i++) - { - char currChar = literalBuffer[i]; - if ((currChar >= '0') && (currChar <= '9')) - { - currByte = (currByte * 10) + (Character.digit(currChar, 10) & 0xFF); - } - - if (currChar == IPV4_LITERAL_SEPARATOR || (i + 1 == literalBuffer.length)) - { - ip[byteCount++] = (byte) currByte; - currByte = 0; - } - } - - if (byteCount != 4) - { - throw new Exception("Invalid IP address: " + address); - } - return ip; - } - private void configureLogging(File logConfigFile, long logWatchTime) throws InitException, IOException { if (logConfigFile.exists() && logConfigFile.canRead()) @@ -447,7 +445,59 @@ public class Broker blm.register(); } - private java.util.logging.Logger updateLogger(final String logType, String logFileName) throws IOException + private void addShutdownHook() + { + Thread shutdownHookThread = new Thread(new ShutdownService()); + shutdownHookThread.setName("QpidBrokerShutdownHook"); + + Runtime.getRuntime().addShutdownHook(shutdownHookThread); + _shutdownHookThread = shutdownHookThread; + + LOGGER.debug("Added shutdown hook"); + } + + private void removeShutdownHook() + { + Thread shutdownThread = _shutdownHookThread; + + //if there is a shutdown thread and we aren't it, we should remove it + if(shutdownThread != null && !(Thread.currentThread() == shutdownThread)) + { + LOGGER.debug("Removing shutdown hook"); + + _shutdownHookThread = null; + + boolean removed = false; + try + { + removed = Runtime.getRuntime().removeShutdownHook(shutdownThread); + } + catch(IllegalStateException ise) + { + //ignore, means the JVM is already shutting down + } + + if(LOGGER.isDebugEnabled()) + { + LOGGER.debug("Removed shutdown hook: " + removed); + } + } + else + { + LOGGER.debug("Skipping shutdown hook removal as there either isnt one, or we are it."); + } + } + + private class ShutdownService implements Runnable + { + public void run() + { + LOGGER.debug("Shutdown hook running"); + Broker.this.shutdown(); + } + } + + private java.util.logging.Logger updateLogger(final String logType, String logFileName) throws IOException { java.util.logging.Logger logger = java.util.logging.Logger.getLogger(logType); logger.setLevel(Level.FINE); @@ -479,4 +529,5 @@ public class Broker logger.addHandler(handler); return logger; } + } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/BrokerOptions.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/BrokerOptions.java index 3defd8260c..a6b1809d3e 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/BrokerOptions.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/BrokerOptions.java @@ -20,23 +20,28 @@ */ package org.apache.qpid.server; +import org.osgi.framework.BundleContext; + import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; -import org.osgi.framework.BundleContext; - public class BrokerOptions { - /** serialVersionUID */ - private static final long serialVersionUID = 8051825964945442234L; - public static final String DEFAULT_CONFIG_FILE = "etc/config.xml"; public static final String DEFAULT_LOG_CONFIG_FILE = "etc/log4j.xml"; public static final String QPID_HOME = "QPID_HOME"; + public static final String PORTS = "p"; + public static final String SSL_PORTS = "s"; + public static final String BIND = "b"; + public static final String MANAGEMENT = "m"; + public static final String LOG_CONFIG = "l"; + public static final String WATCH = "w"; + public static final String CONFIG = "c"; + private final Set _ports = new HashSet(); private final Set _sslPorts = new HashSet(); private final Map> _exclusionMap = new HashMap>(); @@ -50,7 +55,6 @@ public class BrokerOptions private Integer _logWatchFrequency = 0; - public void addPort(final int port) { _ports.add(port); @@ -110,7 +114,6 @@ public class BrokerOptions { _jmxPortConnectorServer = jmxPortConnectorServer; } - public String getQpidHome() { return System.getProperty(QPID_HOME); @@ -157,6 +160,7 @@ public class BrokerOptions _logWatchFrequency = logWatchFrequency; } + public BundleContext getBundleContext() { return _bundleContext ; @@ -166,5 +170,4 @@ public class BrokerOptions { _bundleContext = bundleContext; } - } \ No newline at end of file diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/ExtractResendAndRequeue.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/ExtractResendAndRequeue.java index 9765636c25..0c0b1cf548 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/ExtractResendAndRequeue.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/ExtractResendAndRequeue.java @@ -20,14 +20,15 @@ */ package org.apache.qpid.server; +import org.apache.log4j.Logger; + +import org.apache.qpid.AMQException; import org.apache.qpid.server.ack.UnacknowledgedMessageMap; import org.apache.qpid.server.queue.QueueEntry; import org.apache.qpid.server.store.MessageStore; import org.apache.qpid.server.subscription.Subscription; -import org.apache.qpid.server.txn.ServerTransaction; import org.apache.qpid.server.txn.AutoCommitTransaction; -import org.apache.qpid.AMQException; -import org.apache.log4j.Logger; +import org.apache.qpid.server.txn.ServerTransaction; import java.util.Map; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/Main.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/Main.java index 2bfdd93030..5fcd8a7b52 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/Main.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/Main.java @@ -28,6 +28,8 @@ import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import org.apache.log4j.Logger; +import org.apache.qpid.common.QpidProperties; +import org.apache.qpid.framing.ProtocolVersion; import org.apache.qpid.server.Broker.InitException; import org.apache.qpid.server.registry.ApplicationRegistry; @@ -124,7 +126,7 @@ public class Main OPTIONS.addOption(OPTION_JMX_PORT_CONNECTOR_SERVER); } - private CommandLine commandLine; + protected CommandLine _commandLine; public static void main(String[] args) { @@ -160,7 +162,7 @@ public class Main { try { - commandLine = new PosixParser().parse(OPTIONS, args); + _commandLine = new PosixParser().parse(OPTIONS, args); return true; } @@ -176,66 +178,93 @@ public class Main protected void execute() throws Exception { - BrokerOptions options = new BrokerOptions(); - String configFile = commandLine.getOptionValue(OPTION_CONFIG_FILE.getOpt()); - if(configFile != null) + if (_commandLine.hasOption(OPTION_HELP.getOpt())) { - options.setConfigFile(configFile); + final HelpFormatter formatter = new HelpFormatter(); + formatter.printHelp("Qpid", OPTIONS, true); } - - String logWatchConfig = commandLine.getOptionValue(OPTION_LOG_WATCH.getOpt()); - if(logWatchConfig != null) + else if (_commandLine.hasOption(OPTION_VERSION.getOpt())) { - options.setLogWatchFrequency(Integer.parseInt(logWatchConfig)); - } + final StringBuilder protocol = new StringBuilder("AMQP version(s) [major.minor]: "); + boolean first = true; + for (final ProtocolVersion pv : ProtocolVersion.getSupportedProtocolVersions()) + { + if (first) + { + first = false; + } + else + { + protocol.append(", "); + } - String logConfig = commandLine.getOptionValue(OPTION_LOG_CONFIG_FILE.getOpt()); - if(logConfig != null) - { - options.setLogConfigFile(logConfig); + protocol.append(pv.getMajorVersion()).append('-').append(pv.getMinorVersion()); + } + System.out.println(QpidProperties.getVersionString() + " (" + protocol + ")"); } - - String jmxPortRegistryServer = commandLine.getOptionValue(OPTION_JMX_PORT_REGISTRY_SERVER.getOpt()); - if(jmxPortRegistryServer != null) + else { - options.setJmxPortRegistryServer(Integer.parseInt(jmxPortRegistryServer)); - } + BrokerOptions options = new BrokerOptions(); + String configFile = _commandLine.getOptionValue(OPTION_CONFIG_FILE.getOpt()); + if(configFile != null) + { + options.setConfigFile(configFile); + } - String jmxPortConnectorServer = commandLine.getOptionValue(OPTION_JMX_PORT_CONNECTOR_SERVER.getLongOpt()); - if(jmxPortConnectorServer != null) - { - options.setJmxPortConnectorServer(Integer.parseInt(jmxPortConnectorServer)); - } + String logWatchConfig = _commandLine.getOptionValue(OPTION_LOG_WATCH.getOpt()); + if(logWatchConfig != null) + { + options.setLogWatchFrequency(Integer.parseInt(logWatchConfig)); + } - String bindAddr = commandLine.getOptionValue(OPTION_BIND.getOpt()); - if (bindAddr != null) - { - options.setBind(bindAddr); - } + String logConfig = _commandLine.getOptionValue(OPTION_LOG_CONFIG_FILE.getOpt()); + if(logConfig != null) + { + options.setLogConfigFile(logConfig); + } - String[] portStr = commandLine.getOptionValues(OPTION_PORT.getOpt()); - if(portStr != null) - { - parsePortArray(options, portStr, false); - for(ProtocolExclusion pe : ProtocolExclusion.values()) + String jmxPortRegistryServer = _commandLine.getOptionValue(OPTION_JMX_PORT_REGISTRY_SERVER.getOpt()); + if(jmxPortRegistryServer != null) { - parsePortArray(options, commandLine.getOptionValues(pe.getExcludeName()), pe); + options.setJmxPortRegistryServer(Integer.parseInt(jmxPortRegistryServer)); } - } - String[] sslPortStr = commandLine.getOptionValues(OPTION_SSLPORT.getOpt()); - if(sslPortStr != null) - { - parsePortArray(options, sslPortStr, true); - for(ProtocolExclusion pe : ProtocolExclusion.values()) + String jmxPortConnectorServer = _commandLine.getOptionValue(OPTION_JMX_PORT_CONNECTOR_SERVER.getLongOpt()); + if(jmxPortConnectorServer != null) { - parsePortArray(options, commandLine.getOptionValues(pe.getExcludeName()), pe); + options.setJmxPortConnectorServer(Integer.parseInt(jmxPortConnectorServer)); } - } - - setExceptionHandler(); - - startBroker(options); + + String bindAddr = _commandLine.getOptionValue(OPTION_BIND.getOpt()); + if (bindAddr != null) + { + options.setBind(bindAddr); + } + + String[] portStr = _commandLine.getOptionValues(OPTION_PORT.getOpt()); + if(portStr != null) + { + parsePortArray(options, portStr, false); + for(ProtocolExclusion pe : ProtocolExclusion.values()) + { + parsePortArray(options, _commandLine.getOptionValues(pe.getExcludeName()), pe); + } + } + + String[] sslPortStr = _commandLine.getOptionValues(OPTION_SSLPORT.getOpt()); + if(sslPortStr != null) + { + parsePortArray(options, sslPortStr, true); + for(ProtocolExclusion pe : ProtocolExclusion.values()) + { + parsePortArray(options, _commandLine.getOptionValues(pe.getExcludeName()), pe); + } + } + + setExceptionHandler(); + + startBroker(options); + } } protected void setExceptionHandler() @@ -273,6 +302,7 @@ public class Main { public void uncaughtException(final Thread t, final Throwable e) { + boolean continueOnError = Boolean.getBoolean("qpid.broker.exceptionHandler.continue"); try { System.err.println("########################################################################"); @@ -282,17 +312,20 @@ public class Main System.err.print(" in Thread "); System.err.println(t.getName()); System.err.println("#"); - System.err.println("# Exiting"); + System.err.println(continueOnError ? "# Forced to continue by JVM setting 'qpid.broker.exceptionHandler.continue'" : "# Exiting"); System.err.println("#"); System.err.println("########################################################################"); e.printStackTrace(System.err); Logger logger = Logger.getLogger("org.apache.qpid.server.Main"); - logger.error("Uncaught exception, shutting down.", e); + logger.error("Uncaught exception, " + (continueOnError ? "continuing." : "shutting down."), e); } finally { - Runtime.getRuntime().halt(1); + if (!continueOnError) + { + Runtime.getRuntime().halt(1); + } } } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/ack/UnacknowledgedMessageMap.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/ack/UnacknowledgedMessageMap.java index f4b4932744..842b36cf75 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/ack/UnacknowledgedMessageMap.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/ack/UnacknowledgedMessageMap.java @@ -20,13 +20,12 @@ */ package org.apache.qpid.server.ack; -import java.util.Collection; -import java.util.Set; -import java.util.Map; - import org.apache.qpid.AMQException; import org.apache.qpid.server.queue.QueueEntry; +import java.util.Collection; +import java.util.Set; + public interface UnacknowledgedMessageMap { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/ack/UnacknowledgedMessageMapImpl.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/ack/UnacknowledgedMessageMapImpl.java index 6a5d863526..b8b15c8c28 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/ack/UnacknowledgedMessageMapImpl.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/ack/UnacknowledgedMessageMapImpl.java @@ -20,14 +20,14 @@ */ package org.apache.qpid.server.ack; +import org.apache.qpid.AMQException; +import org.apache.qpid.server.queue.QueueEntry; + import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; -import org.apache.qpid.AMQException; -import org.apache.qpid.server.queue.QueueEntry; - public class UnacknowledgedMessageMapImpl implements UnacknowledgedMessageMap { private final Object _lock = new Object(); diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/binding/Binding.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/binding/Binding.java index 48f85d9bc9..8e44da095a 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/binding/Binding.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/binding/Binding.java @@ -94,7 +94,7 @@ public class Binding return true; } - if (o == null || !(o instanceof Binding)) + if (!(o instanceof Binding)) { return false; } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/binding/BindingFactory.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/binding/BindingFactory.java index 94ab43c851..fe66a6d341 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/binding/BindingFactory.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/binding/BindingFactory.java @@ -20,10 +20,6 @@ */ package org.apache.qpid.server.binding; -import java.util.Collections; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - import org.apache.qpid.AMQException; import org.apache.qpid.AMQInternalException; import org.apache.qpid.AMQSecurityException; @@ -33,8 +29,6 @@ import org.apache.qpid.server.configuration.BindingConfig; import org.apache.qpid.server.configuration.BindingConfigType; import org.apache.qpid.server.configuration.ConfigStore; import org.apache.qpid.server.configuration.ConfiguredObject; -import org.apache.qpid.server.configuration.QueueConfiguration; -import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin; import org.apache.qpid.server.exchange.Exchange; import org.apache.qpid.server.logging.actors.CurrentActor; import org.apache.qpid.server.logging.messages.BindingMessages; @@ -43,6 +37,10 @@ import org.apache.qpid.server.queue.AMQQueue; import org.apache.qpid.server.store.DurableConfigurationStore; import org.apache.qpid.server.virtualhost.VirtualHost; +import java.util.Collections; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + public class BindingFactory { private final VirtualHost _virtualHost; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/BindingConfigType.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/BindingConfigType.java index 5cd064ff42..1ed6b38758 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/BindingConfigType.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/BindingConfigType.java @@ -21,9 +21,11 @@ package org.apache.qpid.server.configuration; -import org.apache.qpid.server.exchange.ExchangeType; - -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Map; public final class BindingConfigType extends ConfigObjectType { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/BridgeConfigType.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/BridgeConfigType.java index a8d3cd9ec3..888feeff0c 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/BridgeConfigType.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/BridgeConfigType.java @@ -21,9 +21,10 @@ package org.apache.qpid.server.configuration; -import org.apache.qpid.server.exchange.ExchangeType; - -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; public final class BridgeConfigType extends ConfigObjectType { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/BrokerConfigType.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/BrokerConfigType.java index e1cf87277b..64a59c3f61 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/BrokerConfigType.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/BrokerConfigType.java @@ -21,7 +21,10 @@ package org.apache.qpid.server.configuration; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; public final class BrokerConfigType extends ConfigObjectType { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/ConfigStore.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/ConfigStore.java index 4e031f0a84..aff07250f3 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/ConfigStore.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/ConfigStore.java @@ -21,9 +21,9 @@ package org.apache.qpid.server.configuration; -import java.util.UUID; import java.util.Collection; import java.util.Collections; +import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicLong; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/ConfigurationManager.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/ConfigurationManager.java index 2c492ff6b9..06402fa646 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/ConfigurationManager.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/ConfigurationManager.java @@ -20,17 +20,18 @@ */ package org.apache.qpid.server.configuration; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.ConfigurationException; + import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin; import org.apache.qpid.server.configuration.plugins.ConfigurationPluginFactory; import org.apache.qpid.server.registry.ApplicationRegistry; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + public class ConfigurationManager { public List getConfigurationPlugins(String configurationElement, Configuration configuration) throws ConfigurationException diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/ConnectionConfigType.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/ConnectionConfigType.java index 9750b12dea..5631fda37c 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/ConnectionConfigType.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/ConnectionConfigType.java @@ -21,9 +21,10 @@ package org.apache.qpid.server.configuration; -import org.apache.qpid.server.exchange.ExchangeType; - -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; public final class ConnectionConfigType extends ConfigObjectType { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/ExchangeConfigType.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/ExchangeConfigType.java index 2095301ad6..c7744117c4 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/ExchangeConfigType.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/ExchangeConfigType.java @@ -21,9 +21,11 @@ package org.apache.qpid.server.configuration; -import org.apache.qpid.server.exchange.ExchangeType; - -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Map; public final class ExchangeConfigType extends ConfigObjectType { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/LinkConfig.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/LinkConfig.java index 0b3a9076dd..2c37a94db0 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/LinkConfig.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/LinkConfig.java @@ -21,11 +21,6 @@ package org.apache.qpid.server.configuration; -import org.apache.qpid.server.exchange.ExchangeType; - -import java.util.Map; - - public interface LinkConfig extends ConfiguredObject { VirtualHostConfig getVirtualHost(); diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/LinkConfigType.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/LinkConfigType.java index 4dc46b70c9..ea4f723dda 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/LinkConfigType.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/LinkConfigType.java @@ -21,9 +21,10 @@ package org.apache.qpid.server.configuration; -import org.apache.qpid.server.exchange.ExchangeType; - -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; public final class LinkConfigType extends ConfigObjectType { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/QueueConfig.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/QueueConfig.java index be34c8d63d..1ef5edeb51 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/QueueConfig.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/QueueConfig.java @@ -21,10 +21,10 @@ package org.apache.qpid.server.configuration; -import java.util.Map; - import org.apache.qpid.AMQException; +import java.util.Map; + public interface QueueConfig extends ConfiguredObject { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/QueueConfigType.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/QueueConfigType.java index a794ed9747..f958ef5350 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/QueueConfigType.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/QueueConfigType.java @@ -21,9 +21,11 @@ package org.apache.qpid.server.configuration; -import org.apache.qpid.server.exchange.ExchangeType; - -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Map; public final class QueueConfigType extends ConfigObjectType { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/QueueConfiguration.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/QueueConfiguration.java index 759907d4bd..a9e45f7415 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/QueueConfiguration.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/QueueConfiguration.java @@ -20,13 +20,14 @@ */ package org.apache.qpid.server.configuration; -import java.util.List; - import org.apache.commons.configuration.CompositeConfiguration; import org.apache.commons.configuration.ConfigurationException; + import org.apache.qpid.exchange.ExchangeDefaults; import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin; +import java.util.List; + public class QueueConfiguration extends ConfigurationPlugin { private String _name; @@ -211,7 +212,7 @@ public class QueueConfiguration extends ConfigurationPlugin public void validateConfiguration() throws ConfigurationException { - if (_configuration.isEmpty()) + if (getConfig().isEmpty()) { throw new ConfigurationException("Queue section cannot be empty."); } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/ServerConfiguration.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/ServerConfiguration.java index d3b89649c7..5d0546f6a7 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/ServerConfiguration.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/ServerConfiguration.java @@ -20,17 +20,6 @@ package org.apache.qpid.server.configuration; -import static org.apache.qpid.transport.ConnectionSettings.WILDCARD_ADDRESS; - -import java.io.File; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Map.Entry; - import org.apache.commons.configuration.CompositeConfiguration; import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.ConfigurationException; @@ -39,14 +28,29 @@ import org.apache.commons.configuration.HierarchicalConfiguration; import org.apache.commons.configuration.SystemConfiguration; import org.apache.commons.configuration.XMLConfiguration; import org.apache.log4j.Logger; + import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin; import org.apache.qpid.server.exchange.DefaultExchangeFactory; +import org.apache.qpid.server.protocol.AmqpProtocolVersion; import org.apache.qpid.server.queue.AMQQueueFactory; import org.apache.qpid.server.registry.ApplicationRegistry; import org.apache.qpid.server.signal.SignalHandlerTask; import org.apache.qpid.server.virtualhost.VirtualHost; import org.apache.qpid.server.virtualhost.VirtualHostRegistry; +import static org.apache.qpid.transport.ConnectionSettings.WILDCARD_ADDRESS; + +import java.io.File; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Map.Entry; + +import javax.net.ssl.KeyManagerFactory; + public class ServerConfiguration extends ConfigurationPlugin { protected static final Logger _logger = Logger.getLogger(ServerConfiguration.class); @@ -84,10 +88,14 @@ public class ServerConfiguration extends ConfigurationPlugin public static final String MGMT_JMXPORT_CONNECTORSERVER = "management.jmxport.connectorServer"; public static final String STATUS_UPDATES = "status-updates"; public static final String ADVANCED_LOCALE = "advanced.locale"; + public static final String CONNECTOR_AMQP010ENABLED = "connector.amqp010enabled"; + public static final String CONNECTOR_AMQP091ENABLED = "connector.amqp091enabled"; + public static final String CONNECTOR_AMQP09ENABLED = "connector.amqp09enabled"; + public static final String CONNECTOR_AMQP08ENABLED = "connector.amqp08enabled"; + public static final String CONNECTOR_AMQP_SUPPORTED_REPLY = "connector.amqpDefaultSupportedProtocolReply"; { envVarMap.put("QPID_PORT", "connector.port"); - envVarMap.put("QPID_ENABLEDIRECTBUFFERS", "advanced.enableDirectBuffers"); envVarMap.put("QPID_SSLPORT", "connector.ssl.port"); envVarMap.put("QPID_JMXPORT_REGISTRYSERVER", MGMT_JMXPORT_REGISTRYSERVER); envVarMap.put("QPID_JMXPORT_CONNECTORSERVER", MGMT_JMXPORT_CONNECTORSERVER); @@ -108,7 +116,6 @@ public class ServerConfiguration extends ConfigurationPlugin envVarMap.put("QPID_SOCKETRECEIVEBUFFER", "connector.socketReceiveBuffer"); envVarMap.put("QPID_SOCKETWRITEBUFFER", "connector.socketWriteBuffer"); envVarMap.put("QPID_TCPNODELAY", "connector.tcpNoDelay"); - envVarMap.put("QPID_ENABLEPOOLEDALLOCATOR", "advanced.enablePooledAllocator"); envVarMap.put("QPID_STATUS-UPDATES", "status-updates"); } @@ -177,7 +184,7 @@ public class ServerConfiguration extends ConfigurationPlugin */ public ServerConfiguration(Configuration conf) { - _configuration = conf; + setConfig(conf); } /** @@ -197,8 +204,8 @@ public class ServerConfiguration extends ConfigurationPlugin */ public void initialise() throws ConfigurationException { - setConfiguration("", _configuration); - setupVirtualHosts(_configuration); + setConfiguration("", getConfig()); + setupVirtualHosts(getConfig()); } public String[] getElementsProcessed() @@ -256,6 +263,13 @@ public class ServerConfiguration extends ConfigurationPlugin + (_configFile == null ? "" : " Configuration file : " + _configFile)); } } + + // QPID-3739 certType was a misleading name. + if (contains("connector.ssl.certType")) + { + _logger.warn("Validation warning: connector/ssl/certType is deprecated and must be replaced by connector/ssl/keyManagerFactoryAlgorithm" + + (_configFile == null ? "" : " Configuration file : " + _configFile)); + } } /* @@ -303,7 +317,7 @@ public class ServerConfiguration extends ConfigurationPlugin // save the default virtualhost name String defaultVirtualHost = vhostConfiguration.getString("default"); - _configuration.setProperty("virtualhosts.default", defaultVirtualHost); + getConfig().setProperty("virtualhosts.default", defaultVirtualHost); } } @@ -472,7 +486,7 @@ public class ServerConfiguration extends ConfigurationPlugin { VirtualHost vhost = vhostRegistry.getVirtualHost(hostName); Configuration vhostConfig = newVhosts.subset("virtualhost." + hostName); - vhost.getConfiguration().setConfiguration("virtualhosts.virtualhost", vhostConfig); // XXX + vhost.getConfiguration().setConfiguration("virtualhosts.virtualhost", vhostConfig); vhost.getSecurityManager().configureGlobalPlugins(this); vhost.getSecurityManager().configureHostPlugins(vhost.getConfiguration()); } @@ -608,11 +622,6 @@ public class ServerConfiguration extends ConfigurationPlugin return getDoubleValue("heartbeat.timeoutFactor", 2.0); } - public int getDeliveryPoolSize() - { - return getIntValue("delivery.poolsize"); - } - public long getMaximumMessageAge() { return getLongValue("maximumMessageAge"); @@ -698,11 +707,6 @@ public class ServerConfiguration extends ConfigurationPlugin return getBooleanValue("connector.tcpNoDelay", true); } - public boolean getEnableExecutorPool() - { - return getBooleanValue("advanced.filterchain[@enableExecutorPool]"); - } - public boolean getEnableSSL() { return getBooleanValue("connector.ssl.enabled"); @@ -730,9 +734,12 @@ public class ServerConfiguration extends ConfigurationPlugin return getStringValue("connector.ssl.keyStorePassword", fallback); } - public String getConnectorCertType() + public String getConnectorKeyManagerFactoryAlgorithm() { - return getStringValue("connector.ssl.certType", "SunX509"); + final String systemFallback = KeyManagerFactory.getDefaultAlgorithm(); + // deprecated, pre-0.17 brokers supported this name. + final String fallback = getStringValue("connector.ssl.certType", systemFallback); + return getStringValue("connector.ssl.keyManagerFactoryAlgorithm", fallback); } public String getDefaultVirtualHost() @@ -836,4 +843,33 @@ public class ServerConfiguration extends ConfigurationPlugin return getConfig().getString("deadLetterQueueSuffix", AMQQueueFactory.DEFAULT_DLQ_NAME_SUFFIX); } + public boolean isAmqp010enabled() + { + return getConfig().getBoolean(CONNECTOR_AMQP010ENABLED, true); + } + + public boolean isAmqp091enabled() + { + return getConfig().getBoolean(CONNECTOR_AMQP091ENABLED, true); + } + + public boolean isAmqp09enabled() + { + return getConfig().getBoolean(CONNECTOR_AMQP09ENABLED, true); + } + + public boolean isAmqp08enabled() + { + return getConfig().getBoolean(CONNECTOR_AMQP08ENABLED, true); + } + + /** + * Returns the configured default reply to an unsupported AMQP protocol initiation, or null if there is none + */ + public AmqpProtocolVersion getDefaultSupportedProtocolReply() + { + String reply = getConfig().getString(CONNECTOR_AMQP_SUPPORTED_REPLY, null); + + return reply == null ? null : AmqpProtocolVersion.valueOf(reply); + } } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/ServerNetworkTransportConfiguration.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/ServerNetworkTransportConfiguration.java index 81dfcb4465..f6fe47b996 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/ServerNetworkTransportConfiguration.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/ServerNetworkTransportConfiguration.java @@ -19,22 +19,21 @@ */ package org.apache.qpid.server.configuration; +import java.net.InetSocketAddress; import org.apache.qpid.transport.NetworkTransportConfiguration; public class ServerNetworkTransportConfiguration implements NetworkTransportConfiguration { private final ServerConfiguration _serverConfig; - private final int _port; - private final String _host; private final String _transport; + private InetSocketAddress _address; public ServerNetworkTransportConfiguration(final ServerConfiguration serverConfig, - final int port, final String host, + final InetSocketAddress address, final String transport) { _serverConfig = serverConfig; - _port = port; - _host = host; + _address = address; _transport = transport; } @@ -55,12 +54,12 @@ public class ServerNetworkTransportConfiguration implements NetworkTransportConf public Integer getPort() { - return _port; + return _address.getPort(); } public String getHost() { - return _host; + return _address.getHostName(); } public String getTransport() @@ -72,4 +71,9 @@ public class ServerNetworkTransportConfiguration implements NetworkTransportConf { return _serverConfig.getConnectorProcessors(); } + + public InetSocketAddress getAddress() + { + return _address; + } } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/SessionConfigType.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/SessionConfigType.java index 97cf275575..1685cfab60 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/SessionConfigType.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/SessionConfigType.java @@ -21,9 +21,10 @@ package org.apache.qpid.server.configuration; -import org.apache.qpid.server.exchange.ExchangeType; - -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; public final class SessionConfigType extends ConfigObjectType { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/SubscriptionConfigType.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/SubscriptionConfigType.java index 99d3273b55..7b7848dd87 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/SubscriptionConfigType.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/SubscriptionConfigType.java @@ -22,7 +22,11 @@ package org.apache.qpid.server.configuration; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Map; public final class SubscriptionConfigType extends ConfigObjectType { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/SystemConfigImpl.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/SystemConfigImpl.java index 09ebb07105..98109ce1e8 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/SystemConfigImpl.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/SystemConfigImpl.java @@ -21,11 +21,11 @@ package org.apache.qpid.server.configuration; -import java.util.UUID; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; import java.net.InetAddress; import java.net.UnknownHostException; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; public class SystemConfigImpl implements SystemConfig { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/SystemConfigType.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/SystemConfigType.java index f5aabd2345..d7c36da4e0 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/SystemConfigType.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/SystemConfigType.java @@ -21,7 +21,11 @@ package org.apache.qpid.server.configuration; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.UUID; public final class SystemConfigType extends ConfigObjectType { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/TopicConfig.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/TopicConfig.java index d5420d9718..10e40151b0 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/TopicConfig.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/TopicConfig.java @@ -22,13 +22,14 @@ package org.apache.qpid.server.configuration; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.PropertiesConfiguration; + import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin; public class TopicConfig extends ConfigurationPlugin { public TopicConfig() { - _configuration = new PropertiesConfiguration(); + setConfig(new PropertiesConfiguration()); } @Override @@ -50,7 +51,7 @@ public class TopicConfig extends ConfigurationPlugin public void validateConfiguration() throws ConfigurationException { - if (_configuration.isEmpty()) + if (getConfig().isEmpty()) { throw new ConfigurationException("Topic section cannot be empty."); } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/TopicConfiguration.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/TopicConfiguration.java index 8716fed8c1..feafd3de1d 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/TopicConfiguration.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/TopicConfiguration.java @@ -22,6 +22,7 @@ package org.apache.qpid.server.configuration; import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.ConfigurationException; + import org.apache.qpid.server.binding.Binding; import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin; import org.apache.qpid.server.configuration.plugins.ConfigurationPluginFactory; @@ -56,8 +57,8 @@ public class TopicConfiguration extends ConfigurationPlugin implements ExchangeC } } - Map _topics = new HashMap(); - Map> _subscriptions = new HashMap>(); + private Map _topics = new HashMap(); + private Map> _subscriptions = new HashMap>(); public String[] getElementsProcessed() { @@ -67,17 +68,17 @@ public class TopicConfiguration extends ConfigurationPlugin implements ExchangeC @Override public void validateConfiguration() throws ConfigurationException { - if (_configuration.isEmpty()) + if (getConfig().isEmpty()) { throw new ConfigurationException("Topics section cannot be empty."); } - int topics = _configuration.getList("topic.name").size() + - _configuration.getList("topic.subscriptionName").size(); + int topics = getConfig().getList("topic.name").size() + + getConfig().getList("topic.subscriptionName").size(); for (int index = 0; index < topics; index++) { - Configuration topicSubset = _configuration.subset("topic(" + index + ")"); + Configuration topicSubset = getConfig().subset("topic(" + index + ")"); // This will occur when we have a subscriptionName that is bound to a // topic. @@ -90,8 +91,8 @@ public class TopicConfiguration extends ConfigurationPlugin implements ExchangeC topic.setConfiguration(VIRTUALHOSTS_VIRTUALHOST_TOPICS + ".topic", topicSubset ); - String name = _configuration.getString("topic(" + index + ").name"); - String subscriptionName = _configuration.getString("topic(" + index + ").subscriptionName"); + String name = getConfig().getString("topic(" + index + ").name"); + String subscriptionName = getConfig().getString("topic(" + index + ").subscriptionName"); // Record config if subscriptionName is there if (subscriptionName != null) diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/VirtualHostConfigType.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/VirtualHostConfigType.java index 96682335bf..16e08e3934 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/VirtualHostConfigType.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/VirtualHostConfigType.java @@ -21,7 +21,10 @@ package org.apache.qpid.server.configuration; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; public class VirtualHostConfigType extends ConfigObjectType { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/VirtualHostConfiguration.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/VirtualHostConfiguration.java index c4e4f701a8..558311fc46 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/VirtualHostConfiguration.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/VirtualHostConfiguration.java @@ -20,17 +20,11 @@ */ package org.apache.qpid.server.configuration; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - import org.apache.commons.configuration.CompositeConfiguration; import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.PropertiesConfiguration; + import org.apache.qpid.exchange.ExchangeDefaults; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.server.binding.Binding; @@ -39,11 +33,18 @@ import org.apache.qpid.server.queue.AMQQueue; import org.apache.qpid.server.registry.ApplicationRegistry; import org.apache.qpid.server.store.MemoryMessageStore; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + public class VirtualHostConfiguration extends ConfigurationPlugin { - private String _name; - private Map _queues = new HashMap(); - private Map _exchanges = new HashMap(); + private final String _name; + private final Map _queues = new HashMap(); + private final Map _exchanges = new HashMap(); public VirtualHostConfiguration(String name, Configuration config) throws ConfigurationException { @@ -75,7 +76,7 @@ public class VirtualHostConfiguration extends ConfigurationPlugin { CompositeConfiguration mungedConf = new CompositeConfiguration(); mungedConf.addConfiguration(config.subset("exchanges.exchange(" + count++ + ")")); - mungedConf.addConfiguration(_configuration.subset("exchanges")); + mungedConf.addConfiguration(getConfig().subset("exchanges")); String exchName = (String) i.next(); _exchanges.put(exchName, new ExchangeConfiguration(exchName, mungedConf)); } @@ -91,11 +92,6 @@ public class VirtualHostConfiguration extends ConfigurationPlugin return getLongValue("housekeeping.checkPeriod", ApplicationRegistry.getInstance().getConfiguration().getHousekeepingCheckPeriod()); } - public String getAuthenticationDatabase() - { - return getStringValue("security.authentication.name"); - } - public List getCustomExchanges() { return getListValue("custom-exchanges.class-name"); @@ -103,7 +99,7 @@ public class VirtualHostConfiguration extends ConfigurationPlugin public Configuration getStoreConfiguration() { - return _configuration.subset("store"); + return getConfig().subset("store"); } public String getMessageStoreClass() @@ -113,7 +109,7 @@ public class VirtualHostConfiguration extends ConfigurationPlugin public void setMessageStoreClass(String storeClass) { - _configuration.setProperty("store.class", storeClass); + getConfig().setProperty("store.class", storeClass); } public List getExchanges() @@ -252,16 +248,6 @@ public class VirtualHostConfiguration extends ConfigurationPlugin return queueConfig; } - public long getMemoryUsageMaximum() - { - return getLongValue("queues.maximumMemoryUsage"); - } - - public long getMemoryUsageMinimum() - { - return getLongValue("queues.minimumMemoryUsage"); - } - public int getMaximumMessageAge() { return getIntValue("queues.maximumMessageAge"); diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/management/ConfigurationManagementMBean.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/management/ConfigurationManagementMBean.java index cc402d5b4a..f0ca5dc139 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/management/ConfigurationManagementMBean.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/management/ConfigurationManagementMBean.java @@ -20,13 +20,12 @@ */ package org.apache.qpid.server.configuration.management; -import javax.management.NotCompliantMBeanException; - -import org.apache.commons.configuration.ConfigurationException; import org.apache.qpid.management.common.mbeans.ConfigurationManagement; import org.apache.qpid.server.management.AMQManagedObject; import org.apache.qpid.server.registry.ApplicationRegistry; +import javax.management.NotCompliantMBeanException; + public class ConfigurationManagementMBean extends AMQManagedObject implements ConfigurationManagement { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/ConfigurationPlugin.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/ConfigurationPlugin.java index b4f82649b0..d08e3bc806 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/ConfigurationPlugin.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/ConfigurationPlugin.java @@ -22,6 +22,7 @@ import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.ConversionException; import org.apache.log4j.Logger; + import org.apache.qpid.server.configuration.ConfigurationManager; import org.apache.qpid.server.registry.ApplicationRegistry; import org.apache.qpid.server.registry.IApplicationRegistry; @@ -42,7 +43,7 @@ public abstract class ConfigurationPlugin private Map _pluginConfiguration = new HashMap(); - protected Configuration _configuration; + private Configuration _config; /** * The Elements that this Plugin can process. @@ -65,7 +66,7 @@ public abstract class ConfigurationPlugin public Configuration getConfig() { - return _configuration; + return _config; } public C getConfiguration(String plugin) @@ -81,7 +82,7 @@ public abstract class ConfigurationPlugin */ public void setConfiguration(String path, Configuration configuration) throws ConfigurationException { - _configuration = configuration; + _config = configuration; // Extract a list of elements for processing Iterator keys = configuration.getKeys(); @@ -215,7 +216,7 @@ public abstract class ConfigurationPlugin protected boolean hasConfiguration() { - return _configuration != null; + return _config != null; } /// Getters @@ -227,7 +228,7 @@ public abstract class ConfigurationPlugin protected double getDoubleValue(String property, double defaultValue) { - return _configuration.getDouble(property, defaultValue); + return _config.getDouble(property, defaultValue); } protected long getLongValue(String property) @@ -237,7 +238,7 @@ public abstract class ConfigurationPlugin protected long getLongValue(String property, long defaultValue) { - return _configuration.getLong(property, defaultValue); + return _config.getLong(property, defaultValue); } protected int getIntValue(String property) @@ -247,7 +248,7 @@ public abstract class ConfigurationPlugin protected int getIntValue(String property, int defaultValue) { - return _configuration.getInt(property, defaultValue); + return _config.getInt(property, defaultValue); } protected String getStringValue(String property) @@ -257,7 +258,7 @@ public abstract class ConfigurationPlugin protected String getStringValue(String property, String defaultValue) { - return _configuration.getString(property, defaultValue); + return _config.getString(property, defaultValue); } protected boolean getBooleanValue(String property) @@ -267,7 +268,7 @@ public abstract class ConfigurationPlugin protected boolean getBooleanValue(String property, boolean defaultValue) { - return _configuration.getBoolean(property, defaultValue); + return _config.getBoolean(property, defaultValue); } protected List getListValue(String property) @@ -277,14 +278,14 @@ public abstract class ConfigurationPlugin protected List getListValue(String property, List defaultValue) { - return _configuration.getList(property, defaultValue); + return _config.getList(property, defaultValue); } /// Validation Helpers protected boolean contains(String property) { - return _configuration.getProperty(property) != null; + return _config.getProperty(property) != null; } /** @@ -323,7 +324,7 @@ public abstract class ConfigurationPlugin throw new ConfigurationException(this.getClass().getSimpleName() + ": unable to configure invalid " + property + ":" + - _configuration.getString(property), + _config.getString(property), last); } } @@ -332,7 +333,7 @@ public abstract class ConfigurationPlugin { try { - _configuration.getLong(property); + _config.getLong(property); return true; } catch (NoSuchElementException e) @@ -345,7 +346,7 @@ public abstract class ConfigurationPlugin { try { - long value = _configuration.getLong(property); + long value = _config.getLong(property); return value > 0; } catch (NoSuchElementException e) @@ -359,7 +360,7 @@ public abstract class ConfigurationPlugin { try { - _configuration.getInt(property); + _config.getInt(property); return true; } catch (NoSuchElementException e) @@ -372,7 +373,7 @@ public abstract class ConfigurationPlugin { try { - _configuration.getBoolean(property); + _config.getBoolean(property); return true; } catch (NoSuchElementException e) @@ -453,7 +454,7 @@ public abstract class ConfigurationPlugin protected void mergeConfiguration(ConfigurationPlugin configuration) { - _configuration = configuration.getConfig(); + _config = configuration.getConfig(); } public String toString() @@ -478,6 +479,10 @@ public abstract class ConfigurationPlugin return super.toString(); } + protected void setConfig(Configuration config) + { + _config = config; + } } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/ConfigurationPluginFactory.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/ConfigurationPluginFactory.java index 02560b296e..fa41f3ef06 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/ConfigurationPluginFactory.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/ConfigurationPluginFactory.java @@ -20,11 +20,11 @@ */ package org.apache.qpid.server.configuration.plugins; -import java.util.List; - import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.ConfigurationException; +import java.util.List; + public interface ConfigurationPluginFactory { /** diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/SlowConsumerDetectionConfiguration.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/SlowConsumerDetectionConfiguration.java index 7a2632d923..a90b1d514f 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/SlowConsumerDetectionConfiguration.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/SlowConsumerDetectionConfiguration.java @@ -22,9 +22,6 @@ package org.apache.qpid.server.configuration.plugins; import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.configuration.ConversionException; -import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin; -import org.apache.qpid.server.configuration.plugins.ConfigurationPluginFactory; import java.util.Arrays; import java.util.List; @@ -48,7 +45,7 @@ public class SlowConsumerDetectionConfiguration extends ConfigurationPlugin } //Set Default time unit to seconds - TimeUnit _timeUnit = TimeUnit.SECONDS; + private TimeUnit _timeUnit = TimeUnit.SECONDS; public String[] getElementsProcessed() { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/SlowConsumerDetectionPolicyConfiguration.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/SlowConsumerDetectionPolicyConfiguration.java index ca8dec851a..a9026c6164 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/SlowConsumerDetectionPolicyConfiguration.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/SlowConsumerDetectionPolicyConfiguration.java @@ -22,8 +22,6 @@ package org.apache.qpid.server.configuration.plugins; import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.ConfigurationException; -import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin; -import org.apache.qpid.server.configuration.plugins.ConfigurationPluginFactory; import java.util.Arrays; import java.util.List; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/SlowConsumerDetectionQueueConfiguration.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/SlowConsumerDetectionQueueConfiguration.java index 6f8020fc54..cb3bb5a77f 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/SlowConsumerDetectionQueueConfiguration.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/SlowConsumerDetectionQueueConfiguration.java @@ -22,8 +22,7 @@ package org.apache.qpid.server.configuration.plugins; import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.ConfigurationException; -import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin; -import org.apache.qpid.server.configuration.plugins.ConfigurationPluginFactory; + import org.apache.qpid.server.plugins.PluginManager; import org.apache.qpid.server.registry.ApplicationRegistry; import org.apache.qpid.slowconsumerdetection.policies.SlowConsumerPolicyPlugin; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/connection/ConnectionRegistry.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/connection/ConnectionRegistry.java index 1c01ce465d..9159489299 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/connection/ConnectionRegistry.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/connection/ConnectionRegistry.java @@ -20,18 +20,18 @@ */ package org.apache.qpid.server.connection; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; - import org.apache.log4j.Logger; + import org.apache.qpid.AMQException; import org.apache.qpid.common.Closeable; import org.apache.qpid.protocol.AMQConstant; import org.apache.qpid.server.protocol.AMQConnectionModel; -import org.apache.qpid.server.protocol.AMQProtocolEngine; import org.apache.qpid.transport.TransportException; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + public class ConnectionRegistry implements IConnectionRegistry, Closeable { private List _registry = new CopyOnWriteArrayList(); diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/connection/IConnectionRegistry.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/connection/IConnectionRegistry.java index b4f5bffa57..89582e5748 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/connection/IConnectionRegistry.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/connection/IConnectionRegistry.java @@ -20,12 +20,12 @@ */ package org.apache.qpid.server.connection; -import java.util.List; - import org.apache.qpid.AMQException; import org.apache.qpid.protocol.AMQConstant; import org.apache.qpid.server.protocol.AMQConnectionModel; +import java.util.List; + public interface IConnectionRegistry { public void initialise(); diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/AbstractExchange.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/AbstractExchange.java index 5ff90b3499..cae07046fa 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/AbstractExchange.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/AbstractExchange.java @@ -41,7 +41,6 @@ import org.apache.qpid.server.queue.QueueRegistry; import org.apache.qpid.server.virtualhost.VirtualHost; import javax.management.JMException; -import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; @@ -62,20 +61,20 @@ public abstract class AbstractExchange implements Exchange, Managable private Exchange _alternateExchange; - protected boolean _durable; - protected int _ticket; + private boolean _durable; + private int _ticket; private VirtualHost _virtualHost; private final List _closeTaskList = new CopyOnWriteArrayList(); - protected AbstractExchangeMBean _exchangeMbean; + private AbstractExchangeMBean _exchangeMbean; /** * Whether the exchange is automatically deleted once all queues have detached from it */ - protected boolean _autoDelete; + private boolean _autoDelete; //The logSubject for ths exchange private LogSubject _logSubject; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/AbstractExchangeMBean.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/AbstractExchangeMBean.java index 0f1b709475..034331abd9 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/AbstractExchangeMBean.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/AbstractExchangeMBean.java @@ -20,29 +20,31 @@ */ package org.apache.qpid.server.exchange; -import java.util.Collections; -import java.util.Map; - import org.apache.qpid.AMQException; -import org.apache.qpid.AMQSecurityException; +import org.apache.qpid.framing.AMQShortString; +import org.apache.qpid.management.common.mbeans.ManagedExchange; +import org.apache.qpid.server.logging.actors.CurrentActor; +import org.apache.qpid.server.logging.actors.ManagementActor; import org.apache.qpid.server.management.AMQManagedObject; import org.apache.qpid.server.management.ManagedObject; import org.apache.qpid.server.management.ManagedObjectRegistry; +import org.apache.qpid.server.queue.AMQQueue; import org.apache.qpid.server.registry.ApplicationRegistry; import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.binding.BindingFactory; -import org.apache.qpid.server.logging.actors.CurrentActor; -import org.apache.qpid.server.logging.actors.ManagementActor; -import org.apache.qpid.management.common.mbeans.ManagedExchange; -import org.apache.qpid.framing.AMQShortString; -import javax.management.openmbean.*; +import javax.management.JMException; import javax.management.MBeanException; +import javax.management.MalformedObjectNameException; import javax.management.NotCompliantMBeanException; import javax.management.ObjectName; -import javax.management.MalformedObjectNameException; -import javax.management.JMException; +import javax.management.openmbean.ArrayType; +import javax.management.openmbean.CompositeType; +import javax.management.openmbean.OpenDataException; +import javax.management.openmbean.OpenType; +import javax.management.openmbean.SimpleType; +import javax.management.openmbean.TabularType; +import java.util.Collections; + /** * Abstract MBean class. This has some of the methods implemented from @@ -52,9 +54,9 @@ import javax.management.JMException; public abstract class AbstractExchangeMBean extends AMQManagedObject implements ManagedExchange { // open mbean data types for representing exchange bindings - protected OpenType[] _bindingItemTypes; - protected CompositeType _bindingDataType; - protected TabularType _bindinglistDataType; + private OpenType[] _bindingItemTypes; + private CompositeType _bindingDataType; + private TabularType _bindinglistDataType; private T _exchange; @@ -105,17 +107,17 @@ public abstract class AbstractExchangeMBean extends public Integer getTicketNo() { - return _exchange._ticket; + return _exchange.getTicket(); } public boolean isDurable() { - return _exchange._durable; + return _exchange.isDurable(); } public boolean isAutoDelete() { - return _exchange._autoDelete; + return _exchange.isAutoDelete(); } // Added exchangetype in the object name lets maangement apps to do any customization required @@ -140,7 +142,7 @@ public abstract class AbstractExchangeMBean extends throw new JMException("Queue \"" + queueName + "\" is not registered with the virtualhost."); } - CurrentActor.set(new ManagementActor(_logActor.getRootMessageLogger())); + CurrentActor.set(new ManagementActor(getLogActor().getRootMessageLogger())); try { vhost.getBindingFactory().addBinding(binding,queue,getExchange(),null); @@ -156,7 +158,7 @@ public abstract class AbstractExchangeMBean extends /** * Removes a queue binding from the exchange. * - * @see BindingFactory#removeBinding(String, AMQQueue, Exchange, Map) + * @see org.apache.qpid.server.binding.BindingFactory#removeBinding(String, AMQQueue, Exchange, java.util.Map) */ public void removeBinding(String queueName, String binding) throws JMException { @@ -167,7 +169,7 @@ public abstract class AbstractExchangeMBean extends throw new JMException("Queue \"" + queueName + "\" is not registered with the virtualhost."); } - CurrentActor.set(new ManagementActor(_logActor.getRootMessageLogger())); + CurrentActor.set(new ManagementActor(getLogActor().getRootMessageLogger())); try { vhost.getBindingFactory().removeBinding(binding, queue, _exchange, Collections.emptyMap()); @@ -179,4 +181,35 @@ public abstract class AbstractExchangeMBean extends } CurrentActor.remove(); } + + + protected OpenType[] getBindingItemTypes() + { + return _bindingItemTypes; + } + + protected void setBindingItemTypes(OpenType[] bindingItemTypes) + { + _bindingItemTypes = bindingItemTypes; + } + + protected CompositeType getBindingDataType() + { + return _bindingDataType; + } + + protected void setBindingDataType(CompositeType bindingDataType) + { + _bindingDataType = bindingDataType; + } + + protected TabularType getBindinglistDataType() + { + return _bindinglistDataType; + } + + protected void setBindinglistDataType(TabularType bindinglistDataType) + { + _bindinglistDataType = bindinglistDataType; + } } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/DefaultExchangeFactory.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/DefaultExchangeFactory.java index 090c0426cf..153419de1b 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/DefaultExchangeFactory.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/DefaultExchangeFactory.java @@ -20,23 +20,22 @@ */ package org.apache.qpid.server.exchange; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - import org.apache.log4j.Logger; -import org.apache.qpid.AMQConnectionException; + import org.apache.qpid.AMQException; import org.apache.qpid.AMQSecurityException; import org.apache.qpid.AMQUnknownExchangeType; import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.protocol.AMQConstant; import org.apache.qpid.qmf.ManagementExchange; import org.apache.qpid.server.configuration.VirtualHostConfiguration; import org.apache.qpid.server.registry.ApplicationRegistry; import org.apache.qpid.server.virtualhost.VirtualHost; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + public class DefaultExchangeFactory implements ExchangeFactory { private static final Logger _logger = Logger.getLogger(DefaultExchangeFactory.class); diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/DefaultExchangeRegistry.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/DefaultExchangeRegistry.java index 8d2dee5aaa..a5fa9f014e 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/DefaultExchangeRegistry.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/DefaultExchangeRegistry.java @@ -20,20 +20,20 @@ */ package org.apache.qpid.server.exchange; -import java.util.Collection; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - import org.apache.log4j.Logger; + import org.apache.qpid.AMQException; import org.apache.qpid.AMQSecurityException; import org.apache.qpid.exchange.ExchangeDefaults; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.server.queue.IncomingMessage; import org.apache.qpid.server.store.DurableConfigurationStore; import org.apache.qpid.server.virtualhost.VirtualHost; +import java.util.Collection; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + public class DefaultExchangeRegistry implements ExchangeRegistry { private static final Logger _log = Logger.getLogger(DefaultExchangeRegistry.class); @@ -153,24 +153,4 @@ public class DefaultExchangeRegistry implements ExchangeRegistry } } - - /** - * Routes content through exchanges, delivering it to 1 or more queues. - * @param payload - * @throws AMQException if something goes wrong delivering data - */ - public void routeContent(IncomingMessage payload) throws AMQException - { - final AMQShortString exchange = payload.getExchange(); - final Exchange exch = getExchange(exchange); - // there is a small window of opportunity for the exchange to be deleted in between - // the BasicPublish being received (where the exchange is validated) and the final - // content body being received (which triggers this method) - // TODO: check where the exchange is validated - if (exch == null) - { - throw new AMQException("Exchange '" + exchange + "' does not exist"); - } - payload.enqueue(exch.route(payload)); - } } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/DirectExchangeMBean.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/DirectExchangeMBean.java index 94fc44d9c7..0bfaf7035d 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/DirectExchangeMBean.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/DirectExchangeMBean.java @@ -20,16 +20,20 @@ */ package org.apache.qpid.server.exchange; -import org.apache.qpid.management.common.mbeans.annotations.MBeanDescription; import org.apache.qpid.management.common.mbeans.annotations.MBeanConstructor; +import org.apache.qpid.management.common.mbeans.annotations.MBeanDescription; import org.apache.qpid.server.binding.Binding; import javax.management.JMException; -import javax.management.openmbean.*; -import java.util.List; -import java.util.Map; +import javax.management.openmbean.CompositeData; +import javax.management.openmbean.CompositeDataSupport; +import javax.management.openmbean.OpenDataException; +import javax.management.openmbean.TabularData; +import javax.management.openmbean.TabularDataSupport; import java.util.ArrayList; import java.util.HashMap; +import java.util.List; +import java.util.Map; /** * MBean class implementing the management interfaces. @@ -47,7 +51,7 @@ final class DirectExchangeMBean extends AbstractExchangeMBean public TabularData bindings() throws OpenDataException { - TabularDataSupport bindingList = new TabularDataSupport(_bindinglistDataType); + TabularDataSupport bindingList = new TabularDataSupport(getBindinglistDataType()); Map> bindingMap = new HashMap>(); @@ -67,7 +71,7 @@ final class DirectExchangeMBean extends AbstractExchangeMBean for(Map.Entry> entry : bindingMap.entrySet()) { Object[] bindingItemValues = {entry.getKey(), entry.getValue().toArray(new String[0])}; - CompositeData bindingData = new CompositeDataSupport(_bindingDataType, + CompositeData bindingData = new CompositeDataSupport(getBindingDataType(), COMPOSITE_ITEM_NAMES.toArray(new String[COMPOSITE_ITEM_NAMES.size()]), bindingItemValues); bindingList.put(bindingData); diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/Exchange.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/Exchange.java index 29c354feae..0bcfc3a3da 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/Exchange.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/Exchange.java @@ -25,18 +25,17 @@ import org.apache.qpid.AMQInternalException; import org.apache.qpid.AMQSecurityException; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.framing.FieldTable; - +import org.apache.qpid.server.binding.Binding; +import org.apache.qpid.server.configuration.ExchangeConfig; +import org.apache.qpid.server.message.InboundMessage; import org.apache.qpid.server.queue.AMQQueue; import org.apache.qpid.server.queue.BaseQueue; import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.server.message.InboundMessage; -import org.apache.qpid.server.binding.Binding; -import org.apache.qpid.server.configuration.ExchangeConfig; import javax.management.JMException; -import java.util.ArrayList; import java.util.Collection; import java.util.List; +import java.util.Map; public interface Exchange extends ExchangeReferrer, ExchangeConfig { @@ -113,6 +112,8 @@ public interface Exchange extends ExchangeReferrer, ExchangeConfig boolean isBound(String bindingKey, AMQQueue queue); + public boolean isBound(String bindingKey, Map arguments, AMQQueue queue); + boolean isBound(String bindingKey); void addCloseTask(Task task); diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeFactory.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeFactory.java index 92795487e4..577da79028 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeFactory.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeFactory.java @@ -20,12 +20,12 @@ */ package org.apache.qpid.server.exchange; -import java.util.Collection; - import org.apache.qpid.AMQException; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.server.configuration.VirtualHostConfiguration; +import java.util.Collection; + public interface ExchangeFactory { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeRegistry.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeRegistry.java index e34ef29d9b..18eb37e037 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeRegistry.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeRegistry.java @@ -26,7 +26,7 @@ import org.apache.qpid.framing.AMQShortString; import java.util.Collection; -public interface ExchangeRegistry extends MessageRouter +public interface ExchangeRegistry { void registerExchange(Exchange exchange) throws AMQException; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeType.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeType.java index 0b55caa2f1..ce339c4e29 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeType.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/ExchangeType.java @@ -20,8 +20,8 @@ */ package org.apache.qpid.server.exchange; -import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.AMQException; +import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.server.virtualhost.VirtualHost; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/FanoutExchangeMBean.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/FanoutExchangeMBean.java index 2c85b7f787..61e23c896c 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/FanoutExchangeMBean.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/FanoutExchangeMBean.java @@ -20,12 +20,16 @@ */ package org.apache.qpid.server.exchange; -import org.apache.qpid.management.common.mbeans.annotations.MBeanDescription; import org.apache.qpid.management.common.mbeans.annotations.MBeanConstructor; +import org.apache.qpid.management.common.mbeans.annotations.MBeanDescription; import org.apache.qpid.server.binding.Binding; import javax.management.JMException; -import javax.management.openmbean.*; +import javax.management.openmbean.CompositeData; +import javax.management.openmbean.CompositeDataSupport; +import javax.management.openmbean.OpenDataException; +import javax.management.openmbean.TabularData; +import javax.management.openmbean.TabularDataSupport; import java.util.ArrayList; /** @@ -46,7 +50,7 @@ final class FanoutExchangeMBean extends AbstractExchangeMBean public TabularData bindings() throws OpenDataException { - TabularDataSupport bindingList = new TabularDataSupport(_bindinglistDataType); + TabularDataSupport bindingList = new TabularDataSupport(getBindinglistDataType()); ArrayList queueNames = new ArrayList(); @@ -58,7 +62,7 @@ final class FanoutExchangeMBean extends AbstractExchangeMBean } Object[] bindingItemValues = {BINDING_KEY_SUBSTITUTE, queueNames.toArray(new String[0])}; - CompositeData bindingData = new CompositeDataSupport(_bindingDataType, + CompositeData bindingData = new CompositeDataSupport(getBindingDataType(), COMPOSITE_ITEM_NAMES.toArray(new String[COMPOSITE_ITEM_NAMES.size()]), bindingItemValues); bindingList.put(bindingData); diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/HeadersBinding.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/HeadersBinding.java index f58a6513a9..b6f5f973f4 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/HeadersBinding.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/HeadersBinding.java @@ -20,17 +20,18 @@ */ package org.apache.qpid.server.exchange; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - import org.apache.log4j.Logger; + import org.apache.qpid.framing.AMQTypedValue; import org.apache.qpid.framing.FieldTable; import org.apache.qpid.server.binding.Binding; import org.apache.qpid.server.message.AMQMessageHeader; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + /** * Defines binding and matching based on a set of headers. */ @@ -38,7 +39,7 @@ class HeadersBinding { private static final Logger _logger = Logger.getLogger(HeadersBinding.class); - private final FieldTable _mappings; + private final Map _mappings; private final Binding _binding; private final Set required = new HashSet(); private final Map matches = new HashMap(); @@ -57,7 +58,7 @@ class HeadersBinding _binding = binding; if(_binding !=null) { - _mappings = FieldTable.convertToFieldTable(_binding.getArguments()); + _mappings = _binding.getArguments(); initMappings(); } else @@ -68,37 +69,23 @@ class HeadersBinding private void initMappings() { - _mappings.processOverElements(new FieldTable.FieldTableElementProcessor() + for(Map.Entry entry : _mappings.entrySet()) { - - public boolean processElement(String propertyName, AMQTypedValue value) + String propertyName = entry.getKey(); + Object value = entry.getValue(); + if (isSpecial(propertyName)) { - if (isSpecial(propertyName)) - { - processSpecial(propertyName, value.getValue()); - } - else if (value.getValue() == null || value.getValue().equals("")) - { - required.add(propertyName); - } - else - { - matches.put(propertyName,value.getValue()); - } - - return true; + processSpecial(propertyName, value); } - - public Object getResult() + else if (value == null || value.equals("")) { - return null; + required.add(propertyName); } - }); - } - - protected FieldTable getMappings() - { - return _mappings; + else + { + matches.put(propertyName,value); + } + } } public Binding getBinding() @@ -206,8 +193,14 @@ class HeadersBinding { if(value instanceof String) { - if("any".equalsIgnoreCase((String) value)) return true; - if("all".equalsIgnoreCase((String) value)) return false; + if("any".equalsIgnoreCase((String) value)) + { + return true; + } + if("all".equalsIgnoreCase((String) value)) + { + return false; + } } _logger.warn("Ignoring unrecognised match type: " + value); return false;//default to all diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/HeadersExchange.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/HeadersExchange.java index f9cbfeb78b..295a7191e7 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/HeadersExchange.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/HeadersExchange.java @@ -21,23 +21,24 @@ 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.AMQShortString; import org.apache.qpid.framing.FieldTable; +import org.apache.qpid.server.binding.Binding; +import org.apache.qpid.server.message.AMQMessageHeader; +import org.apache.qpid.server.message.InboundMessage; import org.apache.qpid.server.queue.AMQQueue; import org.apache.qpid.server.queue.BaseQueue; import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.server.message.InboundMessage; -import org.apache.qpid.server.message.AMQMessageHeader; -import org.apache.qpid.server.binding.Binding; import javax.management.JMException; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.Map; -import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArraySet; /** @@ -145,6 +146,33 @@ public class HeadersExchange extends AbstractExchange return new ArrayList(queues); } + + public boolean isBound(String bindingKey, Map arguments, AMQQueue queue) + { + CopyOnWriteArraySet bindings; + if(bindingKey == null) + { + bindings = new CopyOnWriteArraySet(getBindings()); + } + else + { + bindings = _bindingsByKey.get(bindingKey); + } + + if(bindings != null) + { + for(Binding binding : bindings) + { + if(queue == null || binding.getQueue().equals(queue)) + { + return arguments == null ? binding.getArguments() == null : binding.getArguments().equals(arguments); + } + } + } + + return false; + } + public boolean isBound(AMQShortString routingKey, FieldTable arguments, AMQQueue queue) { //fixme isBound here should take the arguements in to consideration. @@ -250,10 +278,11 @@ public class HeadersExchange extends AbstractExchange { bindings.remove(binding); } - + + boolean removedBinding = _bindingHeaderMatchers.remove(new HeadersBinding(binding)); if(_logger.isDebugEnabled()) { - _logger.debug("Removing Binding: " + _bindingHeaderMatchers.remove(new HeadersBinding(binding))); + _logger.debug("Removing Binding: " + removedBinding); } } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/HeadersExchangeMBean.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/HeadersExchangeMBean.java index caed8f4b94..395c6c8a91 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/HeadersExchangeMBean.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/HeadersExchangeMBean.java @@ -22,8 +22,8 @@ package org.apache.qpid.server.exchange; import org.apache.qpid.AMQException; import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.management.common.mbeans.annotations.MBeanDescription; import org.apache.qpid.management.common.mbeans.annotations.MBeanConstructor; +import org.apache.qpid.management.common.mbeans.annotations.MBeanDescription; import org.apache.qpid.server.binding.Binding; import org.apache.qpid.server.logging.actors.CurrentActor; import org.apache.qpid.server.logging.actors.ManagementActor; @@ -32,11 +32,19 @@ import org.apache.qpid.server.virtualhost.VirtualHost; import javax.management.JMException; import javax.management.MBeanException; -import javax.management.openmbean.*; - +import javax.management.openmbean.ArrayType; +import javax.management.openmbean.CompositeData; +import javax.management.openmbean.CompositeDataSupport; +import javax.management.openmbean.CompositeType; +import javax.management.openmbean.OpenDataException; +import javax.management.openmbean.OpenType; +import javax.management.openmbean.SimpleType; +import javax.management.openmbean.TabularData; +import javax.management.openmbean.TabularDataSupport; +import javax.management.openmbean.TabularType; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; -import java.util.ArrayList; import java.util.Map; /** @@ -60,20 +68,20 @@ final class HeadersExchangeMBean extends AbstractExchangeMBean protected void init() throws OpenDataException { - _bindingItemTypes = new OpenType[3]; - _bindingItemTypes[0] = SimpleType.INTEGER; - _bindingItemTypes[1] = SimpleType.STRING; - _bindingItemTypes[2] = new ArrayType(1, SimpleType.STRING); - _bindingDataType = new CompositeType("Exchange Binding", "Queue name and header bindings", - HEADERS_COMPOSITE_ITEM_NAMES.toArray(new String[HEADERS_COMPOSITE_ITEM_NAMES.size()]), - HEADERS_COMPOSITE_ITEM_DESC.toArray(new String[HEADERS_COMPOSITE_ITEM_DESC.size()]), _bindingItemTypes); - _bindinglistDataType = new TabularType("Exchange Bindings", "List of exchange bindings for " + getName(), - _bindingDataType, HEADERS_TABULAR_UNIQUE_INDEX.toArray(new String[HEADERS_TABULAR_UNIQUE_INDEX.size()])); + setBindingItemTypes(new OpenType[3]); + getBindingItemTypes()[0] = SimpleType.INTEGER; + getBindingItemTypes()[1] = SimpleType.STRING; + getBindingItemTypes()[2] = new ArrayType(1, SimpleType.STRING); + setBindingDataType(new CompositeType("Exchange Binding", "Queue name and header bindings", + HEADERS_COMPOSITE_ITEM_NAMES.toArray(new String[HEADERS_COMPOSITE_ITEM_NAMES.size()]), + HEADERS_COMPOSITE_ITEM_DESC.toArray(new String[HEADERS_COMPOSITE_ITEM_DESC.size()]), getBindingItemTypes())); + setBindinglistDataType(new TabularType("Exchange Bindings", "List of exchange bindings for " + getName(), + getBindingDataType(), HEADERS_TABULAR_UNIQUE_INDEX.toArray(new String[HEADERS_TABULAR_UNIQUE_INDEX.size()]))); } public TabularData bindings() throws OpenDataException { - TabularDataSupport bindingList = new TabularDataSupport(_bindinglistDataType); + TabularDataSupport bindingList = new TabularDataSupport(getBindinglistDataType()); int count = 1; for (Binding binding : getExchange().getBindings()) { @@ -95,7 +103,7 @@ final class HeadersExchangeMBean extends AbstractExchangeMBean Object[] bindingItemValues = {count++, queueName, mappingList.toArray(new String[0])}; - CompositeData bindingData = new CompositeDataSupport(_bindingDataType, + CompositeData bindingData = new CompositeDataSupport(getBindingDataType(), HEADERS_COMPOSITE_ITEM_NAMES.toArray(new String[HEADERS_COMPOSITE_ITEM_NAMES.size()]), bindingItemValues); bindingList.put(bindingData); } @@ -113,7 +121,7 @@ final class HeadersExchangeMBean extends AbstractExchangeMBean throw new JMException("Queue \"" + queueName + "\" is not registered with the virtualhost."); } - CurrentActor.set(new ManagementActor(_logActor.getRootMessageLogger())); + CurrentActor.set(new ManagementActor(getLogActor().getRootMessageLogger())); final Map arguments = new HashMap(); final String[] bindings = binding.split(","); diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/MessageRouter.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/MessageRouter.java deleted file mode 100644 index 025a8014aa..0000000000 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/MessageRouter.java +++ /dev/null @@ -1,40 +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 org.apache.qpid.AMQException; -import org.apache.qpid.server.queue.IncomingMessage; - -/** - * Separated out from the ExchangeRegistry interface to allow components - * that use only this part to have a dependency with a reduced footprint. - * - */ -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(IncomingMessage message) throws AMQException; -} diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/TopicExchange.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/TopicExchange.java index 3a8a86e654..27166e4384 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/TopicExchange.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/TopicExchange.java @@ -20,29 +20,39 @@ */ package org.apache.qpid.server.exchange; +import java.lang.ref.WeakReference; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.WeakHashMap; +import java.util.concurrent.ConcurrentHashMap; +import javax.management.JMException; import org.apache.log4j.Logger; - import org.apache.qpid.AMQException; import org.apache.qpid.AMQInvalidArgumentException; import org.apache.qpid.common.AMQPFilterTypes; import org.apache.qpid.exchange.ExchangeDefaults; +import org.apache.qpid.filter.SelectorParsingException; +import org.apache.qpid.filter.selector.ParseException; +import org.apache.qpid.filter.selector.TokenMgrError; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.BaseQueue; -import org.apache.qpid.server.virtualhost.VirtualHost; import org.apache.qpid.server.binding.Binding; -import org.apache.qpid.server.exchange.topic.*; +import org.apache.qpid.server.exchange.topic.TopicExchangeResult; +import org.apache.qpid.server.exchange.topic.TopicMatcherResult; +import org.apache.qpid.server.exchange.topic.TopicNormalizer; +import org.apache.qpid.server.exchange.topic.TopicParser; import org.apache.qpid.server.filter.JMSSelectorFilter; +import org.apache.qpid.server.filter.MessageFilter; import org.apache.qpid.server.message.InboundMessage; - -import javax.management.JMException; -import java.sql.Array; -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicLong; - -import java.lang.ref.WeakReference; +import org.apache.qpid.server.protocol.AMQSessionModel; +import org.apache.qpid.server.queue.AMQQueue; +import org.apache.qpid.server.queue.BaseQueue; +import org.apache.qpid.server.queue.Filterable; +import org.apache.qpid.server.virtualhost.VirtualHost; public class TopicExchange extends AbstractExchange { @@ -113,24 +123,26 @@ public class TopicExchange extends AbstractExchange FieldTable oldArgs = _bindings.get(binding); TopicExchangeResult result = _topicExchangeResults.get(routingKey); - if(argumentsContainSelector(args)) + if(argumentsContainFilter(args)) { - if(argumentsContainSelector(oldArgs)) + if(argumentsContainFilter(oldArgs)) { - result.replaceQueueFilter(queue,createSelectorFilter(oldArgs), createSelectorFilter(args)); + result.replaceQueueFilter(queue, + createMessageFilter(oldArgs, queue), + createMessageFilter(args, queue)); } else { - result.addFilteredQueue(queue,createSelectorFilter(args)); + result.addFilteredQueue(queue, createMessageFilter(args, queue)); result.removeUnfilteredQueue(queue); } } else { - if(argumentsContainSelector(oldArgs)) + if(argumentsContainFilter(oldArgs)) { result.addUnfilteredQueue(queue); - result.removeFilteredQueue(queue, createSelectorFilter(oldArgs)); + result.removeFilteredQueue(queue, createMessageFilter(oldArgs, queue)); } else { @@ -149,9 +161,9 @@ public class TopicExchange extends AbstractExchange if(result == null) { result = new TopicExchangeResult(); - if(argumentsContainSelector(args)) + if(argumentsContainFilter(args)) { - result.addFilteredQueue(queue, createSelectorFilter(args)); + result.addFilteredQueue(queue, createMessageFilter(args, queue)); } else { @@ -162,9 +174,9 @@ public class TopicExchange extends AbstractExchange } else { - if(argumentsContainSelector(args)) + if(argumentsContainFilter(args)) { - result.addFilteredQueue(queue, createSelectorFilter(args)); + result.addFilteredQueue(queue, createMessageFilter(args, queue)); } else { @@ -178,26 +190,74 @@ public class TopicExchange extends AbstractExchange } - private JMSSelectorFilter createSelectorFilter(final FieldTable args) throws AMQInvalidArgumentException + private MessageFilter createMessageFilter(final FieldTable args, AMQQueue queue) throws AMQInvalidArgumentException { + if(argumentsContainNoLocal(args)) + { + MessageFilter filter = new NoLocalFilter(queue); + + if(argumentsContainJMSSelector(args)) + { + filter = new CompoundFilter(filter, createJMSSelectorFilter(args)); + } + return filter; + } + else + { + return createJMSSelectorFilter(args); + } + + } + + private MessageFilter createJMSSelectorFilter(FieldTable args) throws AMQInvalidArgumentException + { final String selectorString = args.getString(AMQPFilterTypes.JMS_SELECTOR.getValue()); WeakReference selectorRef = _selectorCache.get(selectorString); JMSSelectorFilter selector = null; if(selectorRef == null || (selector = selectorRef.get())==null) { - selector = new JMSSelectorFilter(selectorString); + try + { + selector = new JMSSelectorFilter(selectorString); + } + catch (ParseException e) + { + throw new AMQInvalidArgumentException("Cannot parse JMS selector \"" + selectorString + "\"", e); + } + catch (SelectorParsingException e) + { + throw new AMQInvalidArgumentException("Cannot parse JMS selector \"" + selectorString + "\"", e); + } + catch (TokenMgrError e) + { + throw new AMQInvalidArgumentException("Cannot parse JMS selector \"" + selectorString + "\"", e); + } _selectorCache.put(selectorString, new WeakReference(selector)); } return selector; } - private static boolean argumentsContainSelector(final FieldTable args) + private static boolean argumentsContainFilter(final FieldTable args) { - return args != null && args.containsKey(AMQPFilterTypes.JMS_SELECTOR.getValue()) && args.getString(AMQPFilterTypes.JMS_SELECTOR.getValue()).trim().length() != 0; + return argumentsContainNoLocal(args) || argumentsContainJMSSelector(args); } + private static boolean argumentsContainNoLocal(final FieldTable args) + { + return args != null + && args.containsKey(AMQPFilterTypes.NO_LOCAL.getValue()) + && Boolean.TRUE.equals(args.get(AMQPFilterTypes.NO_LOCAL.getValue())); + } + + private static boolean argumentsContainJMSSelector(final FieldTable args) + { + return args != null && (args.containsKey(AMQPFilterTypes.JMS_SELECTOR.getValue()) + && args.getString(AMQPFilterTypes.JMS_SELECTOR.getValue()).trim().length() != 0); + } + + public ArrayList doRoute(InboundMessage payload) { @@ -251,6 +311,28 @@ public class TopicExchange extends AbstractExchange } } + public boolean isBound(String bindingKey, Map arguments, AMQQueue queue) + { + Binding binding = new Binding(null, bindingKey, queue, this, arguments); + if (arguments == null) + { + return _bindings.containsKey(binding); + } + else + { + FieldTable o = _bindings.get(binding); + if (o != null) + { + return arguments.equals(FieldTable.convertToMap(o)); + } + else + { + return false; + } + } + + } + public boolean isBound(AMQShortString routingKey, AMQQueue queue) { return isBound(routingKey, null, queue); @@ -297,11 +379,11 @@ public class TopicExchange extends AbstractExchange result.removeBinding(binding); - if(argumentsContainSelector(bindingArgs)) + if(argumentsContainFilter(bindingArgs)) { try { - result.removeFilteredQueue(binding.getQueue(), createSelectorFilter(bindingArgs)); + result.removeFilteredQueue(binding.getQueue(), createMessageFilter(bindingArgs, binding.getQueue())); } catch (AMQInvalidArgumentException e) { @@ -378,4 +460,96 @@ public class TopicExchange extends AbstractExchange deregisterQueue(binding); } + private static final class NoLocalFilter implements MessageFilter + { + private final AMQQueue _queue; + + public NoLocalFilter(AMQQueue queue) + { + _queue = queue; + } + + public boolean matches(Filterable message) + { + InboundMessage inbound = (InboundMessage) message; + final AMQSessionModel exclusiveOwningSession = _queue.getExclusiveOwningSession(); + return exclusiveOwningSession == null || !exclusiveOwningSession.onSameConnection(inbound); + + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + + if (o == null || getClass() != o.getClass()) + { + return false; + } + + NoLocalFilter that = (NoLocalFilter) o; + + return _queue == null ? that._queue == null : _queue.equals(that._queue); + } + + @Override + public int hashCode() + { + return _queue != null ? _queue.hashCode() : 0; + } + } + + private static final class CompoundFilter implements MessageFilter + { + private MessageFilter _noLocalFilter; + private MessageFilter _jmsSelectorFilter; + + public CompoundFilter(MessageFilter filter, MessageFilter jmsSelectorFilter) + { + _noLocalFilter = filter; + _jmsSelectorFilter = jmsSelectorFilter; + } + + public boolean matches(Filterable message) + { + return _noLocalFilter.matches(message) && _jmsSelectorFilter.matches(message); + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (o == null || getClass() != o.getClass()) + { + return false; + } + + CompoundFilter that = (CompoundFilter) o; + + if (_jmsSelectorFilter != null ? !_jmsSelectorFilter.equals(that._jmsSelectorFilter) : that._jmsSelectorFilter != null) + { + return false; + } + if (_noLocalFilter != null ? !_noLocalFilter.equals(that._noLocalFilter) : that._noLocalFilter != null) + { + return false; + } + + return true; + } + + @Override + public int hashCode() + { + int result = _noLocalFilter != null ? _noLocalFilter.hashCode() : 0; + result = 31 * result + (_jmsSelectorFilter != null ? _jmsSelectorFilter.hashCode() : 0); + return result; + } + } } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/TopicExchangeMBean.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/TopicExchangeMBean.java index 620c3ce140..481a377fc4 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/TopicExchangeMBean.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/TopicExchangeMBean.java @@ -20,16 +20,20 @@ */ package org.apache.qpid.server.exchange; -import org.apache.qpid.management.common.mbeans.annotations.MBeanDescription; import org.apache.qpid.management.common.mbeans.annotations.MBeanConstructor; +import org.apache.qpid.management.common.mbeans.annotations.MBeanDescription; import org.apache.qpid.server.binding.Binding; import javax.management.JMException; -import javax.management.openmbean.*; +import javax.management.openmbean.CompositeData; +import javax.management.openmbean.CompositeDataSupport; +import javax.management.openmbean.OpenDataException; +import javax.management.openmbean.TabularData; +import javax.management.openmbean.TabularDataSupport; +import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.HashMap; -import java.util.ArrayList; /** TopicExchangeMBean class implements the management interface for the Topic exchanges. */ @MBeanDescription("Management Bean for Topic Exchange") @@ -47,7 +51,7 @@ final class TopicExchangeMBean extends AbstractExchangeMBean /** returns exchange bindings in tabular form */ public TabularData bindings() throws OpenDataException { - TabularDataSupport bindingList = new TabularDataSupport(_bindinglistDataType); + TabularDataSupport bindingList = new TabularDataSupport(getBindinglistDataType()); Map> bindingData = new HashMap>(); for (Binding binding : getExchange().getBindings()) { @@ -65,7 +69,7 @@ final class TopicExchangeMBean extends AbstractExchangeMBean { Object[] bindingItemValues = {entry.getKey(), entry.getValue().toArray(new String[entry.getValue().size()]) }; CompositeData bindingCompositeData = - new CompositeDataSupport(_bindingDataType, + new CompositeDataSupport(getBindingDataType(), COMPOSITE_ITEM_NAMES.toArray(new String[COMPOSITE_ITEM_NAMES.size()]), bindingItemValues); bindingList.put(bindingCompositeData); diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/headers/HeaderKey.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/headers/HeaderKey.java deleted file mode 100644 index 8fdb91cbef..0000000000 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/headers/HeaderKey.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.apache.qpid.server.exchange.headers; - -import org.apache.qpid.framing.AMQShortString; - -/* -* -* 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. -* -*/ -public class HeaderKey -{ - public static final HeaderKey UNKNOWN = new HeaderKey(new AMQShortString("<< UNKNOWN >>")); - private AMQShortString _key; - - public HeaderKey(final AMQShortString key) - { - _key = key; - } - - public String toString() - { - return _key.toString(); - } - -} diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/headers/HeaderKeyDictionary.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/headers/HeaderKeyDictionary.java deleted file mode 100644 index 7be99a88c9..0000000000 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/headers/HeaderKeyDictionary.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.apache.qpid.server.exchange.headers; - -import org.apache.qpid.framing.AMQShortString; - -import java.util.Map; -import java.util.HashMap; - -/* -* -* 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. -* -*/ -public class HeaderKeyDictionary -{ - - private final Map _dictionary = new HashMap(); - - - public HeaderKey get(final AMQShortString key) - { - HeaderKey headerKey = _dictionary.get(key); - return headerKey == null ? HeaderKey.UNKNOWN : headerKey; - } - - public HeaderKey getOrCreate(final AMQShortString key) - { - HeaderKey headerKey = _dictionary.get(key); - if(headerKey == null) - { - headerKey = new HeaderKey(key); - _dictionary.put(key, headerKey); - } - return headerKey; - } -} diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/headers/HeaderMatcherResult.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/headers/HeaderMatcherResult.java deleted file mode 100644 index 518064bb29..0000000000 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/headers/HeaderMatcherResult.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.apache.qpid.server.exchange.headers; - -/* -* -* 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. -* -*/ -public class HeaderMatcherResult -{ -} diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/headers/HeadersMatcherDFAState.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/headers/HeadersMatcherDFAState.java deleted file mode 100644 index 9da93d483a..0000000000 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/headers/HeadersMatcherDFAState.java +++ /dev/null @@ -1,339 +0,0 @@ -package org.apache.qpid.server.exchange.headers; - -import org.apache.qpid.framing.AMQTypedValue; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.server.exchange.topic.TopicMatcherDFAState; -import org.apache.qpid.server.exchange.topic.TopicWord; -import org.apache.qpid.server.exchange.topic.TopicMatcherResult; - -import java.util.*; - -/* -* -* 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. -* -*/ -public class HeadersMatcherDFAState -{ - - - private final Collection _results; - private final Map> _nextStateMap; - private final HeaderKeyDictionary _dictionary; - - public HeadersMatcherDFAState(Map> nextStateMap, - Collection results, - HeaderKeyDictionary dictionary) - { - _nextStateMap = nextStateMap; - _results = results; - _dictionary = dictionary; - } - - - public Collection match(final FieldTable table) - { - return match(table.iterator()); - } - - - - public Collection match(Iterator> fieldTableIterator) - { - - if(_nextStateMap.isEmpty()) - { - return _results; - } - - while(fieldTableIterator.hasNext()) - { - - Map.Entry fieldTableEntry = fieldTableIterator.next(); - HeaderKey key = _dictionary.get(fieldTableEntry.getKey()); - if(key != HeaderKey.UNKNOWN) - { - Map valueToStateMap = _nextStateMap.get(key); - - if(valueToStateMap != null) - { - HeadersMatcherDFAState nextState = valueToStateMap.get(fieldTableEntry.getValue()); - - if(nextState == null) - { - nextState = valueToStateMap.get(null); - } - if(nextState != null && nextState != this) - { - return nextState.match(fieldTableIterator); - } - } - - } - } - - return _results; - - } - - - HeadersMatcherDFAState mergeStateMachines(HeadersMatcherDFAState otherStateMachine) - { - - assert(otherStateMachine._dictionary == _dictionary); - - Map, HeadersMatcherDFAState> newStateMap= new HashMap, HeadersMatcherDFAState>(); - - Collection results; - - if(_results.isEmpty()) - { - results = otherStateMachine._results; - } - else if(otherStateMachine._results.isEmpty()) - { - results = _results; - } - else - { - results = new HashSet(_results); - results.addAll(otherStateMachine._results); - } - - - final Map> newNextStateMap = new HashMap>(); - - HeadersMatcherDFAState newState = new HeadersMatcherDFAState(newNextStateMap, results, _dictionary); - - - Set oldStates = new HashSet(); - oldStates.add(this); - oldStates.add(otherStateMachine); - - newStateMap.put(oldStates, newState); - - mergeStateMachines(oldStates, newNextStateMap, newStateMap); - - return newState; - - - } - - private void mergeStateMachines(final Set oldStates, - final Map> newNextStateMap, - final Map, HeadersMatcherDFAState> newStateMap) - { - Map>> nfaMap = new HashMap>>(); - - Set distinctKeys = new HashSet(); - - for(HeadersMatcherDFAState state : oldStates) - { - Map> map = state._nextStateMap; - - for(Map.Entry> entry : map.entrySet()) - { - Map> valueToStatesMap = nfaMap.get(entry.getKey()); - - if(valueToStatesMap == null) - { - valueToStatesMap = new HashMap>(); - nfaMap.put(entry.getKey(), valueToStatesMap); - } - - for(Map.Entry valueToStateEntry : entry.getValue().entrySet()) - { - Set states = valueToStatesMap.get(valueToStateEntry.getKey()); - if(states == null) - { - states = new HashSet(); - valueToStatesMap.put(valueToStateEntry.getKey(),states); - } - states.add(valueToStateEntry.getValue()); - } - - distinctKeys.add(entry.getKey()); - } - } - - Map> anyValueStates = new HashMap>(); - - for(HeaderKey distinctKey : distinctKeys) - { - Map> valueToStateMap = nfaMap.get(distinctKey); - if(valueToStateMap != null) - { - Set statesForKeyDefault = valueToStateMap.get(null); - if(statesForKeyDefault != null) - { - anyValueStates.put(distinctKey, statesForKeyDefault); - } - } - } - - // add the defaults for "null" to all other specified values of a given header key - - for( Map.Entry>> entry : nfaMap.entrySet()) - { - Map> valueToStatesMap = entry.getValue(); - for(Map.Entry> valueToStates : valueToStatesMap.entrySet()) - { - if(valueToStates.getKey() != null) - { - - - Set defaults = anyValueStates.get(entry.getKey()); - if(defaults != null) - { - valueToStates.getValue().addAll(defaults); - } - } - } - } - - // if a given header key is not mentioned in the map of a machine; then that machine would stay at the same state - // for that key. - for(HeaderKey distinctKey : distinctKeys) - { - Map> valueToStatesMap = nfaMap.get(distinctKey); - for(HeadersMatcherDFAState oldState : oldStates) - { - if(!oldState._nextStateMap.containsKey(distinctKey)) - { - for(Set endStates : valueToStatesMap.values()) - { - endStates.add(oldState); - } - } - } - } - - - - - for(Map.Entry>> transitionClass : nfaMap.entrySet()) - { - Map valueToDFAState = newNextStateMap.get(transitionClass.getKey()); - if(valueToDFAState == null) - { - valueToDFAState = new HashMap(); - newNextStateMap.put(transitionClass.getKey(), valueToDFAState); - } - - for(Map.Entry> transition : transitionClass.getValue().entrySet()) - { - Set destinations = transition.getValue(); - - - HeadersMatcherDFAState nextState = newStateMap.get(destinations); - - if(nextState == null) - { - - if(destinations.size() == 1) - { - nextState = destinations.iterator().next(); - newStateMap.put(destinations, nextState); - } - else - { - Collection results; - - Set> resultSets = new HashSet>(); - for(HeadersMatcherDFAState destination : destinations) - { - resultSets.add(destination._results); - } - resultSets.remove(Collections.EMPTY_SET); - if(resultSets.size() == 0) - { - results = Collections.EMPTY_SET; - } - else if(resultSets.size() == 1) - { - results = resultSets.iterator().next(); - } - else - { - results = new HashSet(); - for(Collection oldResult : resultSets) - { - results.addAll(oldResult); - } - } - - final Map> nextStateMap = new HashMap>(); - - nextState = new HeadersMatcherDFAState(nextStateMap, results, _dictionary); - newStateMap.put(destinations, nextState); - - mergeStateMachines( - destinations, - nextStateMap, - newStateMap); - - - } - - - } - valueToDFAState.put(transition.getKey(),nextState); - } - } - - - - final ArrayList removeKeyList = new ArrayList(); - - for(Map.Entry> entry : _nextStateMap.entrySet()) - { - final ArrayList removeValueList = new ArrayList(); - - for(Map.Entry valueToDFAState : entry.getValue().entrySet()) - { - if(valueToDFAState.getValue() == this) - { - HeadersMatcherDFAState defaultState = entry.getValue().get(null); - if(defaultState == null || defaultState == this) - { - removeValueList.add(valueToDFAState.getKey()); - } - } - } - - for(AMQTypedValue removeValue : removeValueList) - { - entry.getValue().remove(removeValue); - } - - if(entry.getValue().isEmpty()) - { - removeKeyList.add(entry.getKey()); - } - - } - - for(HeaderKey removeKey : removeKeyList) - { - _nextStateMap.remove(removeKey); - } - - } - -} diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/headers/HeadersParser.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/headers/HeadersParser.java deleted file mode 100644 index d76b163fa1..0000000000 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/headers/HeadersParser.java +++ /dev/null @@ -1,315 +0,0 @@ -package org.apache.qpid.server.exchange.headers; - -import org.apache.qpid.framing.*; - -import java.util.*; - -/* -* -* 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. -* -*/ -public class HeadersParser -{ - - private final HeaderKeyDictionary _dictionary = new HeaderKeyDictionary(); - private static final AMQShortString MATCHING_TYPE_KEY = new AMQShortString("x-match"); - private static final String ANY_MATCHING = "any"; - private static final AMQShortString RESERVED_KEY_PREFIX = new AMQShortString("x-"); - - - HeadersMatcherDFAState createStateMachine(FieldTable bindingArguments, HeaderMatcherResult result) - { - String matchingType = bindingArguments.getString(MATCHING_TYPE_KEY); - boolean matchAny = matchingType.equalsIgnoreCase(ANY_MATCHING); - if(matchAny) - { - return createStateMachineForAnyMatch(bindingArguments, result); - } - else - { - return createStateMachineForAllMatch(bindingArguments, result); - } - - - } - - - private HeadersMatcherDFAState createStateMachineForAnyMatch(final FieldTable bindingArguments, - final HeaderMatcherResult result) - { - - // DFAs for "any" matches have only two states, "not-matched" and "matched"... they start in the former - // and upon meeting any of the criteria they move to the latter - - //noinspection unchecked - final HeadersMatcherDFAState successState = - new HeadersMatcherDFAState(Collections.EMPTY_MAP,Collections.singleton(result),_dictionary); - - Map> nextStateMap = - new HashMap>(); - - Set seenKeys = new HashSet(); - - Iterator> tableIterator = bindingArguments.iterator(); - - while(tableIterator.hasNext()) - { - final Map.Entry entry = tableIterator.next(); - final AMQShortString key = entry.getKey(); - final AMQTypedValue value = entry.getValue(); - - - if(seenKeys.add(key) && !key.startsWith(RESERVED_KEY_PREFIX)) - { - final AMQType type = value.getType(); - - final HeaderKey headerKey = _dictionary.getOrCreate(key); - final Map valueMap; - - if(type == AMQType.VOID || - ((type == AMQType.ASCII_STRING || type == AMQType.WIDE_STRING) && ((CharSequence)value.getValue()).length() == 0)) - { - valueMap = Collections.singletonMap(null,successState); - - } - else - { - valueMap = Collections.singletonMap(value,successState); - } - nextStateMap.put(headerKey,valueMap); - - } - - } - - if(seenKeys.size() == 0) - { - return successState; - } - else - { - return new HeadersMatcherDFAState(nextStateMap,Collections.EMPTY_SET,_dictionary); - } - - - } - - - private HeadersMatcherDFAState createStateMachineForAllMatch(final FieldTable bindingArguments, - final HeaderMatcherResult result) - { - // DFAs for "all" matches have a "success" state, a "fail" state, and states for every subset of - // matches which are possible, starting with the empty subset. For example if we have a binding - // { x-match="all" - // a=1 - // b=1 - // c=1 - // d=1 } - // Then we would have the following states - // (1) Seen none of a, b, c, or d - // (2) Seen a=1 ; none of b,c, or d - // (3) Seen b=1 ; none of a,c, or d - // (4) Seen c=1 ; none of a,b, or d - // (5) Seen d=1 ; none of a,b, or c - // (6) Seen a=1,b=1 ; none of c,d - // (7) Seen a=1,c=1 ; none of b,d - // (8) Seen a=1,d=1 ; none of b,c - // (9) Seen b=1,c=1 ; none of a,d - //(10) Seen b=1,d=1 ; none of c,d - //(11) Seen c=1,d=1 ; none of a,b - //(12) Seen a=1,b=1,c=1 ; not d - //(13) Seen a=1,b=1,d=1 ; not c - //(14) Seen a=1,c=1,d=1 ; not b - //(15) Seen b=1,c=1,d=1 ; not a - //(16) success - //(17) fail - // - // All states but (16) can transition to (17); additionally: - // (1) can transition to (2),(3),(4),(5) - // (2) can transition to (6),(7),(8) - // (3) can transition to (6),(9),(10) - // (4) can transition to (7),(9),(11) - // (5) can transition to (8),(10),(11) - // (6) can transition to (12),(13) - // (7) can transition to (12),(14) - // (8) can transition to (13),(14) - // (9) can transition to (12),(15) - //(10) can transition to (13),(15) - //(11) can transition to (14),(15) - //(12)-(15) can transition to (16) - - Set seenKeys = new HashSet(); - List requiredTerms = new ArrayList(bindingArguments.size()); - - Iterator> tableIterator = bindingArguments.iterator(); - - - - while(tableIterator.hasNext()) - { - final Map.Entry entry = tableIterator.next(); - final AMQShortString key = entry.getKey(); - final AMQTypedValue value = entry.getValue(); - - - if(seenKeys.add(key) && !key.startsWith(RESERVED_KEY_PREFIX)) - { - final AMQType type = value.getType(); - - if(type == AMQType.VOID || - ((type == AMQType.ASCII_STRING || type == AMQType.WIDE_STRING) && ((CharSequence)value.getValue()).length() == 0)) - { - requiredTerms.add(new KeyValuePair(_dictionary.getOrCreate(key),null)); - } - else - { - requiredTerms.add(new KeyValuePair(_dictionary.getOrCreate(key),value)); - } - } - - } - - final HeadersMatcherDFAState successState = - new HeadersMatcherDFAState(Collections.EMPTY_MAP,Collections.singleton(result),_dictionary); - - final HeadersMatcherDFAState failState = - new HeadersMatcherDFAState(Collections.EMPTY_MAP,Collections.EMPTY_SET,_dictionary); - - Map, HeadersMatcherDFAState> notSeenTermsToStateMap = - new HashMap, HeadersMatcherDFAState>(); - - notSeenTermsToStateMap.put(Collections.EMPTY_SET, successState); - - - final int numberOfTerms = requiredTerms.size(); - - for(int numMissingTerms = 1; numMissingTerms <= numberOfTerms; numMissingTerms++) - { - int[] pos = new int[numMissingTerms]; - for(int i = 0; i < numMissingTerms; i++) - { - pos[i] = i; - } - - final int maxTermValue = (numberOfTerms - (numMissingTerms - 1)); - - while(pos[0] < maxTermValue) - { - - Set stateSet = new HashSet(); - for(int posIndex = 0; posIndex < pos.length; posIndex++) - { - stateSet.add(requiredTerms.get(pos[posIndex])); - } - - final Map> nextStateMap = - new HashMap>(); - - - for(int posIndex = 0; posIndex < pos.length; posIndex++) - { - KeyValuePair nextTerm = requiredTerms.get(pos[posIndex]); - HashSet nextStateSet = - new HashSet(stateSet); - nextStateSet.remove(nextTerm); - - Map valueToStateMap = - new HashMap(); - nextStateMap.put(nextTerm._key, valueToStateMap); - - valueToStateMap.put( nextTerm._value,notSeenTermsToStateMap.get(nextStateSet)); - if(nextTerm._value != null) - { - valueToStateMap.put(null, failState); - } - - - } - - - HeadersMatcherDFAState newState = new HeadersMatcherDFAState(nextStateMap, Collections.EMPTY_SET, _dictionary); - - notSeenTermsToStateMap.put(stateSet, newState); - - int i = numMissingTerms; - while(i-- != 0) - { - if(++pos[i] <= numberOfTerms -(numMissingTerms-i)) - { - int k = pos[i]; - for(int j = i+1; j < numMissingTerms; j++) - { - pos[j] = ++k; - } - break; - } - } - } - - - - - } - - - return notSeenTermsToStateMap.get(new HashSet(requiredTerms)); - - - - } - - public final static class KeyValuePair - { - public final HeaderKey _key; - public final AMQTypedValue _value; - private final int _hashCode; - - public KeyValuePair(final HeaderKey key, final AMQTypedValue value) - { - _key = key; - _value = value; - int hash = (1 + 31 * _key.hashCode()); - if(_value != null) - { - hash+=_value.hashCode(); - } - _hashCode = hash; - } - - public int hashCode() - { - return _hashCode; - } - - public boolean equals(Object o) - { - assert o != null; - assert o instanceof KeyValuePair; - KeyValuePair other = (KeyValuePair)o; - return (_key == other._key) && (_value == null ? other._value == null : _value.equals(other._value)); - } - - - public String toString() - { - return "{" + _key + " -> " + _value + "}"; - } - - } -} diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicExchangeResult.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicExchangeResult.java index d8b09a7841..44d5f7f1d0 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicExchangeResult.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicExchangeResult.java @@ -20,10 +20,10 @@ */ package org.apache.qpid.server.exchange.topic; -import org.apache.qpid.server.queue.AMQQueue; import org.apache.qpid.server.binding.Binding; import org.apache.qpid.server.filter.MessageFilter; import org.apache.qpid.server.message.InboundMessage; +import org.apache.qpid.server.queue.AMQQueue; import java.util.ArrayList; import java.util.Collection; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicMatcherDFAState.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicMatcherDFAState.java index 4446536d4c..dfe4d85320 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicMatcherDFAState.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicMatcherDFAState.java @@ -3,7 +3,17 @@ package org.apache.qpid.server.exchange.topic; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.framing.AMQShortStringTokenizer; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; import java.util.concurrent.atomic.AtomicInteger; /* @@ -246,25 +256,25 @@ public class TopicMatcherDFAState transitions.append("[ "); transitions.append(entry.getKey()); transitions.append("\t ->\t "); - transitions.append(entry.getValue()._id); + transitions.append(entry.getValue().getId()); transitions.append(" ]\n"); } - return "[ State " + _id + " ]\n" + transitions + "\n"; + return "[ State " + getId() + " ]\n" + transitions + "\n"; } public String reachableStates() { - StringBuilder result = new StringBuilder("Start state: " + _id + "\n"); + StringBuilder result = new StringBuilder("Start state: " + getId() + "\n"); SortedSet reachableStates = new TreeSet(new Comparator() { public int compare(final TopicMatcherDFAState o1, final TopicMatcherDFAState o2) { - return o1._id - o2._id; + return o1.getId() - o2.getId(); } }); reachableStates.add(this); @@ -292,4 +302,9 @@ public class TopicMatcherDFAState return result.toString(); } + + int getId() + { + return _id; + } } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicNormalizer.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicNormalizer.java index 7e7cb6c0ae..aac696ae2d 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicNormalizer.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicNormalizer.java @@ -22,10 +22,9 @@ package org.apache.qpid.server.exchange.topic; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.framing.AMQShortStringTokenizer; -import org.apache.qpid.server.exchange.TopicExchange; -import java.util.List; import java.util.ArrayList; +import java.util.List; public class TopicNormalizer { @@ -37,6 +36,10 @@ public class TopicNormalizer private static final AMQShortString AMQP_STAR_TOKEN = new AMQShortString("*"); private static final AMQShortString AMQP_HASH_TOKEN = new AMQShortString("#"); + private TopicNormalizer() + { + } + public static AMQShortString normalize(AMQShortString routingKey) { if(routingKey == null) diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicParser.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicParser.java index 3e9facf412..1cb4301838 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicParser.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicParser.java @@ -3,9 +3,15 @@ package org.apache.qpid.server.exchange.topic; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.framing.AMQShortStringTokenizer; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; import java.util.concurrent.atomic.AtomicReference; -import java.io.IOException; /* * @@ -52,14 +58,43 @@ public class TopicParser } + public TopicWord getWord() + { + return _word; + } + + public boolean isSelfTransition() + { + return _selfTransition; + } + + public int getPosition() + { + return _position; + } + + public boolean isEndState() + { + return _endState; + } + + public boolean isFollowedByAnyLoop() + { + return _followedByAnyLoop; + } + + public void setFollowedByAnyLoop(boolean followedByAnyLoop) + { + _followedByAnyLoop = followedByAnyLoop; + } } private static final Position ERROR_POSITION = new Position(Integer.MAX_VALUE,null, true, false); private static class SimpleState { - Set _positions; - Map _nextState; + private Set _positions; + private Map _nextState; } @@ -180,11 +215,11 @@ public class TopicParser while(followedByWildcards && n<(positionCount+1)) { - if(positions[n]._selfTransition) + if(positions[n].isSelfTransition()) { break; } - else if(positions[n]._word!=TopicWord.ANY_WORD) + else if(positions[n].getWord() !=TopicWord.ANY_WORD) { followedByWildcards = false; } @@ -192,7 +227,7 @@ public class TopicParser } - positions[p]._followedByAnyLoop = followedByWildcards && (n!= positionCount+1); + positions[p].setFollowedByAnyLoop(followedByWildcards && (n!= positionCount+1)); } @@ -221,7 +256,7 @@ public class TopicParser for(Position p : simpleStates[i]._positions) { - if(p._endState) + if(p.isEndState()) { endState = true; break; @@ -267,7 +302,7 @@ public class TopicParser for(Position pos : state._positions) { - if(pos._selfTransition) + if(pos.isSelfTransition()) { Set dest = transitions.get(TopicWord.ANY_WORD); if(dest == null) @@ -278,14 +313,14 @@ public class TopicParser dest.add(pos); } - final int nextPos = pos._position + 1; + final int nextPos = pos.getPosition() + 1; Position nextPosition = nextPos == positions.length ? ERROR_POSITION : positions[nextPos]; - Set dest = transitions.get(pos._word); + Set dest = transitions.get(pos.getWord()); if(dest == null) { dest = new HashSet(); - transitions.put(pos._word,dest); + transitions.put(pos.getWord(),dest); } dest.add(nextPosition); @@ -312,7 +347,7 @@ public class TopicParser Position loopingTerminal = null; for(Position destPos : dest.getValue()) { - if(destPos._selfTransition && destPos._endState) + if(destPos.isSelfTransition() && destPos.isEndState()) { loopingTerminal = destPos; break; @@ -328,9 +363,9 @@ public class TopicParser Position anyLoop = null; for(Position destPos : dest.getValue()) { - if(destPos._followedByAnyLoop) + if(destPos.isFollowedByAnyLoop()) { - if(anyLoop == null || anyLoop._position removals = new ArrayList(); for(Position destPos : dest.getValue()) { - if(destPos._position < anyLoop._position) + if(destPos.getPosition() < anyLoop.getPosition()) { removals.add(destPos); } @@ -421,193 +456,4 @@ public class TopicParser } - public static void main(String[] args) - { - - printMatches("#.b.*.*.*.*.*.h.#.j.*.*.*.*.*.*.q.#.r.*.*.*.*.*.*.*.*","a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p.q.r.s.t.u.v.w.x.y.z"); - printMatches(new String[]{ - "#.a.#", - "#.b.#", - "#.c.#", - "#.d.#", - "#.e.#", - "#.f.#", - "#.g.#", - "#.h.#", - "#.i.#", - "#.j.#", - "#.k.#", - "#.l.#", - "#.m.#", - "#.n.#", - "#.o.#", - "#.p.#", - "#.q.#" - - }, "a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p.q.r.s.t.u.v.w.x.y.z"); -/* - printMatches(new String[]{ - "#.a.#", - "#.b.#", - "#.c.#", - "#.d.#", - "#.e.#", - "#.f.#", - "#.g.#", - "#.h.#", - "#.i.#", - "#.j.#", - "#.k.#", - "#.l.#", - "#.m.#", - "#.n.#", - "#.o.#", - "#.p.#", - "#.q.#", - "#.r.#", - "#.s.#", - "#.t.#", - "#.u.#", - "#.v.#", - "#.w.#", - "#.x.#", - "#.y.#", - "#.z.#" - - - },"a.b"); - - printMatches("#.b.*.*.*.*.*.h.#.j.*.*.*.*.*.p.#.r.*.*.*.*.*","a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p.q.r.s.t.u.v.w.x.y.z"); - printMatches("#.b.*.*.*.*.*.h.#.j.*.*.*.*.*.p.#.r.*.*.*.*.*.*.*.*","a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p.q.r.s.t.u.v.w.x.y.z"); - printMatches("a.#.b.#","a.b.b.b.b.b.b.b.c"); - -*/ - - printMatches("",""); - printMatches("a","a"); - printMatches("a",""); - printMatches("","a"); - printMatches("a.b","a.b"); - printMatches("a","a.b"); - printMatches("a.b","a"); - printMatches("*","a"); - printMatches("*.b","a.b"); - printMatches("*.*","a.b"); - printMatches("a.*","a.b"); - printMatches("a.*.#","a.b"); - printMatches("a.#.b","a.b"); - - printMatches("#.b","a"); - printMatches("#.b","a.b"); - printMatches("#.a.b","a.b"); - - - printMatches("#",""); - printMatches("#","a"); - printMatches("#","a.b"); - printMatches("#.#","a.b"); - printMatches("#.*","a.b"); - - printMatches("#.a.b","a.b"); - printMatches("a.b.#","a.b"); - printMatches("a.#","a.b"); - printMatches("#.*.#","a.b"); - printMatches("#.*.b.#","a.b"); - printMatches("#.a.*.#","a.b"); - printMatches("#.a.#.b.#","a.b"); - printMatches("#.*.#.*.#","a.b"); - printMatches("*.#.*.#","a.b"); - printMatches("#.*.#.*","a.b"); - - - printMatches(new String[]{"a.#.b.#","a.*.#.b.#"},"a.b.b.b.b.b.b.b.c"); - - - printMatches(new String[]{"a.b", "a.c"},"a.b"); - printMatches(new String[]{"a.#", "a.c", "#.b"},"a.b"); - printMatches(new String[]{"a.#", "a.c", "#.b", "#", "*.*"},"a.b"); - - printMatches(new String[]{"a.b.c.d.e.#", "a.b.c.d.#", "a.b.c.d.*", "a.b.c.#", "#.e", "a.*.c.d.e","#.c.*.#.*.*"},"a.b.c.d.e"); - printMatches(new String[]{"a.b.c.d.e.#", "a.b.c.d.#", "a.b.c.d.*", "a.b.c.#", "#.e", "a.*.c.d.e","#.c.*.#.*.*"},"a.b.c.d.f.g"); - - - - - } - - private static void printMatches(final String[] bindingKeys, final String routingKey) - { - TopicMatcherDFAState sm = null; - Map resultMap = new HashMap(); - - TopicParser parser = new TopicParser(); - - long start = System.currentTimeMillis(); - for(int i = 0; i < bindingKeys.length; i++) - { - System.out.println((System.currentTimeMillis() - start) + ":\t" + bindingKeys[i]); - TopicMatcherResult r = new TopicMatcherResult(){}; - resultMap.put(r, bindingKeys[i]); - AMQShortString bindingKeyShortString = new AMQShortString(bindingKeys[i]); - - System.err.println("====================================================="); - System.err.println("Adding binding key: " + bindingKeyShortString); - System.err.println("-----------------------------------------------------"); - - - if(i==0) - { - sm = parser.createStateMachine(bindingKeyShortString, r); - } - else - { - sm = sm.mergeStateMachines(parser.createStateMachine(bindingKeyShortString, r)); - } - System.err.println(sm.reachableStates()); - System.err.println("====================================================="); - try - { - System.in.read(); - } - catch (IOException e) - { - e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. - } - } - AMQShortString routingKeyShortString = new AMQShortString(routingKey); - - Collection results = sm.parse(parser._dictionary, routingKeyShortString); - Collection resultStrings = new ArrayList(); - - for(TopicMatcherResult result : results) - { - resultStrings.add(resultMap.get(result)); - } - - final ArrayList nonMatches = new ArrayList(Arrays.asList(bindingKeys)); - nonMatches.removeAll(resultStrings); - System.out.println("\""+routingKeyShortString+"\" matched with " + resultStrings + " DID NOT MATCH with " + nonMatches); - - - } - - private static void printMatches(String bindingKey, String routingKey) - { - printMatches(new String[] { bindingKey }, routingKey); - } - - - private static boolean matches(String bindingKey, String routingKey) - { - AMQShortString bindingKeyShortString = new AMQShortString(bindingKey); - AMQShortString routingKeyShortString = new AMQShortString(routingKey); - TopicParser parser = new TopicParser(); - - final TopicMatcherResult result = new TopicMatcherResult(){}; - - TopicMatcherDFAState sm = parser.createStateMachine(bindingKeyShortString, result); - return !sm.parse(parser._dictionary,routingKeyShortString).isEmpty(); - - } - } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicWord.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicWord.java index f14d70f8a1..b23b3db272 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicWord.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicWord.java @@ -2,10 +2,6 @@ package org.apache.qpid.server.exchange.topic; import org.apache.qpid.framing.AMQShortString; -import java.util.Map; -import java.util.HashMap; -import java.util.concurrent.ConcurrentHashMap; - /* * * Licensed to the Apache Software Foundation (ASF) under one diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/federation/Bridge.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/federation/Bridge.java index 4db6ee3ad2..b58802e1ff 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/federation/Bridge.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/federation/Bridge.java @@ -45,9 +45,28 @@ import org.apache.qpid.server.transport.ServerSession; import org.apache.qpid.server.txn.AutoCommitTransaction; import org.apache.qpid.server.txn.ServerTransaction; import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.transport.*; - -import java.util.*; +import org.apache.qpid.transport.DeliveryProperties; +import org.apache.qpid.transport.MessageAcceptMode; +import org.apache.qpid.transport.MessageAcquireMode; +import org.apache.qpid.transport.MessageCreditUnit; +import org.apache.qpid.transport.MessageFlowMode; +import org.apache.qpid.transport.MessageReject; +import org.apache.qpid.transport.MessageRejectCode; +import org.apache.qpid.transport.MessageTransfer; +import org.apache.qpid.transport.Option; +import org.apache.qpid.transport.RangeSet; +import org.apache.qpid.transport.RangeSetFactory; +import org.apache.qpid.transport.Session; +import org.apache.qpid.transport.SessionException; +import org.apache.qpid.transport.SessionListener; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; @@ -503,7 +522,7 @@ public class Bridge implements BridgeConfig _transaction.enqueue(queues,message, new ServerTransaction.Action() { - BaseQueue[] _queues = queues.toArray(new BaseQueue[queues.size()]); + private BaseQueue[] _queues = queues.toArray(new BaseQueue[queues.size()]); public void postCommit() { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/federation/BrokerLink.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/federation/BrokerLink.java index a8f75d2b9b..032df8bb0d 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/federation/BrokerLink.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/federation/BrokerLink.java @@ -30,8 +30,15 @@ import org.apache.qpid.server.configuration.LinkConfig; import org.apache.qpid.server.configuration.LinkConfigType; import org.apache.qpid.server.transport.ServerSession; import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.transport.*; -import org.apache.qpid.util.Strings; +import org.apache.qpid.transport.Binary; +import org.apache.qpid.transport.ClientDelegate; +import org.apache.qpid.transport.Connection; +import org.apache.qpid.transport.ConnectionException; +import org.apache.qpid.transport.ConnectionListener; +import org.apache.qpid.transport.ConnectionSettings; +import org.apache.qpid.transport.Session; +import org.apache.qpid.transport.SessionDelegate; +import org.apache.qpid.transport.TransportException; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; @@ -42,7 +49,11 @@ import javax.security.sasl.Sasl; import javax.security.sasl.SaslClient; import javax.security.sasl.SaslException; import java.io.IOException; -import java.util.*; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ScheduledThreadPoolExecutor; @@ -365,8 +376,8 @@ public class BrokerLink implements LinkConfig, ConnectionListener } }; final SaslClient sc = Sasl.createSaslClient(new String[] {"PLAIN"}, null, - _conSettings.getSaslProtocol(), - _conSettings.getSaslServerName(), + getConnectionSettings().getSaslProtocol(), + getConnectionSettings().getSaslServerName(), saslProps, cbh); return sc; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/ArithmeticExpression.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/ArithmeticExpression.java deleted file mode 100644 index 221d23ef0d..0000000000 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/ArithmeticExpression.java +++ /dev/null @@ -1,275 +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.filter; -// -// Based on like named file from r450141 of the Apache ActiveMQ project -// - -import org.apache.qpid.AMQException; -import org.apache.qpid.server.queue.Filterable; - -/** - * An expression which performs an operation on two expression values - */ -public abstract class ArithmeticExpression extends BinaryExpression -{ - - protected static final int INTEGER = 1; - protected static final int LONG = 2; - protected static final int DOUBLE = 3; - - /** - * @param left - * @param right - */ - public ArithmeticExpression(Expression left, Expression right) - { - super(left, right); - } - - public static Expression createPlus(Expression left, Expression right) - { - return new ArithmeticExpression(left, right) - { - protected Object evaluate(Object lvalue, Object rvalue) - { - if (lvalue instanceof String) - { - String text = (String) lvalue; - String answer = text + rvalue; - - return answer; - } - else if (lvalue instanceof Number) - { - return plus((Number) lvalue, asNumber(rvalue)); - } - - throw new RuntimeException("Cannot call plus operation on: " + lvalue + " and: " + rvalue); - } - - public String getExpressionSymbol() - { - return "+"; - } - }; - } - - public static Expression createMinus(Expression left, Expression right) - { - return new ArithmeticExpression(left, right) - { - protected Object evaluate(Object lvalue, Object rvalue) - { - if (lvalue instanceof Number) - { - return minus((Number) lvalue, asNumber(rvalue)); - } - - throw new RuntimeException("Cannot call minus operation on: " + lvalue + " and: " + rvalue); - } - - public String getExpressionSymbol() - { - return "-"; - } - }; - } - - public static Expression createMultiply(Expression left, Expression right) - { - return new ArithmeticExpression(left, right) - { - - protected Object evaluate(Object lvalue, Object rvalue) - { - if (lvalue instanceof Number) - { - return multiply((Number) lvalue, asNumber(rvalue)); - } - - throw new RuntimeException("Cannot call multiply operation on: " + lvalue + " and: " + rvalue); - } - - public String getExpressionSymbol() - { - return "*"; - } - }; - } - - public static Expression createDivide(Expression left, Expression right) - { - return new ArithmeticExpression(left, right) - { - - protected Object evaluate(Object lvalue, Object rvalue) - { - if (lvalue instanceof Number) - { - return divide((Number) lvalue, asNumber(rvalue)); - } - - throw new RuntimeException("Cannot call divide operation on: " + lvalue + " and: " + rvalue); - } - - public String getExpressionSymbol() - { - return "/"; - } - }; - } - - public static Expression createMod(Expression left, Expression right) - { - return new ArithmeticExpression(left, right) - { - - protected Object evaluate(Object lvalue, Object rvalue) - { - if (lvalue instanceof Number) - { - return mod((Number) lvalue, asNumber(rvalue)); - } - - throw new RuntimeException("Cannot call mod operation on: " + lvalue + " and: " + rvalue); - } - - public String getExpressionSymbol() - { - return "%"; - } - }; - } - - protected Number plus(Number left, Number right) - { - switch (numberType(left, right)) - { - - case INTEGER: - return Integer.valueOf(left.intValue() + right.intValue()); - - case LONG: - return Long.valueOf(left.longValue() + right.longValue()); - - default: - return Double.valueOf(left.doubleValue() + right.doubleValue()); - } - } - - protected Number minus(Number left, Number right) - { - switch (numberType(left, right)) - { - - case INTEGER: - return Integer.valueOf(left.intValue() - right.intValue()); - - case LONG: - return Long.valueOf(left.longValue() - right.longValue()); - - default: - return Double.valueOf(left.doubleValue() - right.doubleValue()); - } - } - - protected Number multiply(Number left, Number right) - { - switch (numberType(left, right)) - { - - case INTEGER: - return Integer.valueOf(left.intValue() * right.intValue()); - - case LONG: - return Long.valueOf(left.longValue() * right.longValue()); - - default: - return Double.valueOf(left.doubleValue() * right.doubleValue()); - } - } - - protected Number divide(Number left, Number right) - { - return Double.valueOf(left.doubleValue() / right.doubleValue()); - } - - protected Number mod(Number left, Number right) - { - return Double.valueOf(left.doubleValue() % right.doubleValue()); - } - - private int numberType(Number left, Number right) - { - if (isDouble(left) || isDouble(right)) - { - return DOUBLE; - } - else if ((left instanceof Long) || (right instanceof Long)) - { - return LONG; - } - else - { - return INTEGER; - } - } - - private boolean isDouble(Number n) - { - return (n instanceof Float) || (n instanceof Double); - } - - protected Number asNumber(Object value) - { - if (value instanceof Number) - { - return (Number) value; - } - else - { - throw new RuntimeException("Cannot convert value: " + value + " into a number"); - } - } - - public Object evaluate(Filterable message) - { - Object lvalue = left.evaluate(message); - if (lvalue == null) - { - return null; - } - - Object rvalue = right.evaluate(message); - if (rvalue == null) - { - return null; - } - - return evaluate(lvalue, rvalue); - } - - /** - * @param lvalue - * @param rvalue - * @return - */ - protected abstract Object evaluate(Object lvalue, Object rvalue); - -} diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/BinaryExpression.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/BinaryExpression.java deleted file mode 100644 index 024257bea9..0000000000 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/BinaryExpression.java +++ /dev/null @@ -1,106 +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.filter; -// -// Based on like named file from r450141 of the Apache ActiveMQ project -// - -/** - * An expression which performs an operation on two expression values. - */ -public abstract class BinaryExpression implements Expression -{ - protected Expression left; - protected Expression right; - - public BinaryExpression(Expression left, Expression right) - { - this.left = left; - this.right = right; - } - - public Expression getLeft() - { - return left; - } - - public Expression getRight() - { - return right; - } - - /** - * @see java.lang.Object#toString() - */ - public String toString() - { - return "(" + left.toString() + " " + getExpressionSymbol() + " " + right.toString() + ")"; - } - - /** - * TODO: more efficient hashCode() - * - * @see java.lang.Object#hashCode() - */ - public int hashCode() - { - return toString().hashCode(); - } - - /** - * TODO: more efficient hashCode() - * - * @see java.lang.Object#equals(java.lang.Object) - */ - public boolean equals(Object o) - { - - if ((o == null) || !this.getClass().equals(o.getClass())) - { - return false; - } - - return toString().equals(o.toString()); - - } - - /** - * Returns the symbol that represents this binary expression. For example, addition is - * represented by "+" - * - * @return - */ - public abstract String getExpressionSymbol(); - - /** - * @param expression - */ - public void setRight(Expression expression) - { - right = expression; - } - - /** - * @param expression - */ - public void setLeft(Expression expression) - { - left = expression; - } - -} diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/BooleanExpression.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/BooleanExpression.java deleted file mode 100644 index 06e8664470..0000000000 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/BooleanExpression.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.qpid.server.filter; -// -// Based on like named file from r450141 of the Apache ActiveMQ project -// - -import org.apache.qpid.server.queue.Filterable; - -/** - * A BooleanExpression is an expression that always - * produces a Boolean result. - */ -public interface BooleanExpression extends Expression -{ - - /** - * @param message - * @return true if the expression evaluates to Boolean.TRUE. - */ - public boolean matches(Filterable message); - -} diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/ComparisonExpression.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/ComparisonExpression.java deleted file mode 100644 index aad9d41174..0000000000 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/ComparisonExpression.java +++ /dev/null @@ -1,599 +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.filter; -// -// Based on like named file from r450141 of the Apache ActiveMQ project -// - -import java.util.HashSet; -import java.util.List; -import java.util.regex.Pattern; - -import org.apache.qpid.server.queue.Filterable; - -/** - * A filter performing a comparison of two objects - */ -public abstract class ComparisonExpression extends BinaryExpression implements BooleanExpression -{ - - public static BooleanExpression createBetween(Expression value, Expression left, Expression right) - { - return LogicExpression.createAND(createGreaterThanEqual(value, left), createLessThanEqual(value, right)); - } - - public static BooleanExpression createNotBetween(Expression value, Expression left, Expression right) - { - return LogicExpression.createOR(createLessThan(value, left), createGreaterThan(value, right)); - } - - private static final HashSet REGEXP_CONTROL_CHARS = new HashSet(); - - static - { - REGEXP_CONTROL_CHARS.add('.'); - REGEXP_CONTROL_CHARS.add('\\'); - REGEXP_CONTROL_CHARS.add('['); - REGEXP_CONTROL_CHARS.add(']'); - REGEXP_CONTROL_CHARS.add('^'); - REGEXP_CONTROL_CHARS.add('$'); - REGEXP_CONTROL_CHARS.add('?'); - REGEXP_CONTROL_CHARS.add('*'); - REGEXP_CONTROL_CHARS.add('+'); - REGEXP_CONTROL_CHARS.add('{'); - REGEXP_CONTROL_CHARS.add('}'); - REGEXP_CONTROL_CHARS.add('|'); - REGEXP_CONTROL_CHARS.add('('); - REGEXP_CONTROL_CHARS.add(')'); - REGEXP_CONTROL_CHARS.add(':'); - REGEXP_CONTROL_CHARS.add('&'); - REGEXP_CONTROL_CHARS.add('<'); - REGEXP_CONTROL_CHARS.add('>'); - REGEXP_CONTROL_CHARS.add('='); - REGEXP_CONTROL_CHARS.add('!'); - } - - static class LikeExpression extends UnaryExpression implements BooleanExpression - { - - Pattern likePattern; - - /** - * @param right - */ - public LikeExpression(Expression right, String like, int escape) - { - super(right); - - StringBuffer regexp = new StringBuffer(like.length() * 2); - regexp.append("\\A"); // The beginning of the input - for (int i = 0; i < like.length(); i++) - { - char c = like.charAt(i); - if (escape == (0xFFFF & c)) - { - i++; - if (i >= like.length()) - { - // nothing left to escape... - break; - } - - char t = like.charAt(i); - regexp.append("\\x"); - regexp.append(Integer.toHexString(0xFFFF & t)); - } - else if (c == '%') - { - regexp.append(".*?"); // Do a non-greedy match - } - else if (c == '_') - { - regexp.append("."); // match one - } - else if (REGEXP_CONTROL_CHARS.contains(c)) - { - regexp.append("\\x"); - regexp.append(Integer.toHexString(0xFFFF & c)); - } - else - { - regexp.append(c); - } - } - - regexp.append("\\z"); // The end of the input - - likePattern = Pattern.compile(regexp.toString(), Pattern.DOTALL); - } - - /** - * org.apache.activemq.filter.UnaryExpression#getExpressionSymbol() - */ - public String getExpressionSymbol() - { - return "LIKE"; - } - - /** - * org.apache.activemq.filter.Expression#evaluate(MessageEvaluationContext) - */ - public Object evaluate(Filterable message) - { - - Object rv = this.getRight().evaluate(message); - - if (rv == null) - { - return null; - } - - if (!(rv instanceof String)) - { - return - Boolean.FALSE; - // throw new RuntimeException("LIKE can only operate on String identifiers. LIKE attemped on: '" + rv.getClass()); - } - - return likePattern.matcher((String) rv).matches() ? Boolean.TRUE : Boolean.FALSE; - } - - public boolean matches(Filterable message) - { - Object object = evaluate(message); - - return (object != null) && (object == Boolean.TRUE); - } - } - - public static BooleanExpression createLike(Expression left, String right, String escape) - { - if ((escape != null) && (escape.length() != 1)) - { - throw new RuntimeException( - "The ESCAPE string litteral is invalid. It can only be one character. Litteral used: " + escape); - } - - int c = -1; - if (escape != null) - { - c = 0xFFFF & escape.charAt(0); - } - - return new LikeExpression(left, right, c); - } - - public static BooleanExpression createNotLike(Expression left, String right, String escape) - { - return UnaryExpression.createNOT(createLike(left, right, escape)); - } - - public static BooleanExpression createInFilter(Expression left, List elements) - { - - if (!(left instanceof PropertyExpression)) - { - throw new RuntimeException("Expected a property for In expression, got: " + left); - } - - return UnaryExpression.createInExpression((PropertyExpression) left, elements, false); - - } - - public static BooleanExpression createNotInFilter(Expression left, List elements) - { - - if (!(left instanceof PropertyExpression)) - { - throw new RuntimeException("Expected a property for In expression, got: " + left); - } - - return UnaryExpression.createInExpression((PropertyExpression) left, elements, true); - - } - - public static BooleanExpression createIsNull(Expression left) - { - return doCreateEqual(left, ConstantExpression.NULL); - } - - public static BooleanExpression createIsNotNull(Expression left) - { - return UnaryExpression.createNOT(doCreateEqual(left, ConstantExpression.NULL)); - } - - public static BooleanExpression createNotEqual(Expression left, Expression right) - { - return UnaryExpression.createNOT(createEqual(left, right)); - } - - public static BooleanExpression createEqual(Expression left, Expression right) - { - checkEqualOperand(left); - checkEqualOperand(right); - checkEqualOperandCompatability(left, right); - - return doCreateEqual(left, right); - } - - private static BooleanExpression doCreateEqual(Expression left, Expression right) - { - return new EqualExpression(left, right); - } - - public static BooleanExpression createGreaterThan(final Expression left, final Expression right) - { - checkLessThanOperand(left); - checkLessThanOperand(right); - - return new ComparisonExpression(left, right) - { - protected boolean asBoolean(int answer) - { - return answer > 0; - } - - public String getExpressionSymbol() - { - return ">"; - } - }; - } - - public static BooleanExpression createGreaterThanEqual(final Expression left, final Expression right) - { - checkLessThanOperand(left); - checkLessThanOperand(right); - - return new ComparisonExpression(left, right) - { - protected boolean asBoolean(int answer) - { - return answer >= 0; - } - - public String getExpressionSymbol() - { - return ">="; - } - }; - } - - public static BooleanExpression createLessThan(final Expression left, final Expression right) - { - checkLessThanOperand(left); - checkLessThanOperand(right); - - return new ComparisonExpression(left, right) - { - - protected boolean asBoolean(int answer) - { - return answer < 0; - } - - public String getExpressionSymbol() - { - return "<"; - } - - }; - } - - public static BooleanExpression createLessThanEqual(final Expression left, final Expression right) - { - checkLessThanOperand(left); - checkLessThanOperand(right); - - return new ComparisonExpression(left, right) - { - - protected boolean asBoolean(int answer) - { - return answer <= 0; - } - - public String getExpressionSymbol() - { - return "<="; - } - }; - } - - /** - * Only Numeric expressions can be used in >, >=, < or <= expressions.s - * - * @param expr - */ - public static void checkLessThanOperand(Expression expr) - { - if (expr instanceof ConstantExpression) - { - Object value = ((ConstantExpression) expr).getValue(); - if (value instanceof Number) - { - return; - } - - // Else it's boolean or a String.. - throw new RuntimeException("Value '" + expr + "' cannot be compared."); - } - - if (expr instanceof BooleanExpression) - { - throw new RuntimeException("Value '" + expr + "' cannot be compared."); - } - } - - /** - * Validates that the expression can be used in == or <> expression. - * Cannot not be NULL TRUE or FALSE litterals. - * - * @param expr - */ - public static void checkEqualOperand(Expression expr) - { - if (expr instanceof ConstantExpression) - { - Object value = ((ConstantExpression) expr).getValue(); - if (value == null) - { - throw new RuntimeException("'" + expr + "' cannot be compared."); - } - } - } - - /** - * - * @param left - * @param right - */ - private static void checkEqualOperandCompatability(Expression left, Expression right) - { - if ((left instanceof ConstantExpression) && (right instanceof ConstantExpression)) - { - if ((left instanceof BooleanExpression) && !(right instanceof BooleanExpression)) - { - throw new RuntimeException("'" + left + "' cannot be compared with '" + right + "'"); - } - } - } - - /** - * @param left - * @param right - */ - public ComparisonExpression(Expression left, Expression right) - { - super(left, right); - } - - public Object evaluate(Filterable message) - { - Comparable lv = (Comparable) left.evaluate(message); - if (lv == null) - { - return null; - } - - Comparable rv = (Comparable) right.evaluate(message); - if (rv == null) - { - return null; - } - - return compare(lv, rv); - } - - protected Boolean compare(Comparable lv, Comparable rv) - { - Class lc = lv.getClass(); - Class rc = rv.getClass(); - // If the the objects are not of the same type, - // try to convert up to allow the comparison. - if (lc != rc) - { - if (lc == Byte.class) - { - if (rc == Short.class) - { - lv = ((Number) lv).shortValue(); - } - else if (rc == Integer.class) - { - lv = ((Number) lv).intValue(); - } - else if (rc == Long.class) - { - lv = ((Number) lv).longValue(); - } - else if (rc == Float.class) - { - lv = ((Number) lv).floatValue(); - } - else if (rc == Double.class) - { - lv = ((Number) lv).doubleValue(); - } - else - { - return Boolean.FALSE; - } - } - else if (lc == Short.class) - { - if (rc == Integer.class) - { - lv = ((Number) lv).intValue(); - } - else if (rc == Long.class) - { - lv = ((Number) lv).longValue(); - } - else if (rc == Float.class) - { - lv = ((Number) lv).floatValue(); - } - else if (rc == Double.class) - { - lv = ((Number) lv).doubleValue(); - } - else - { - return Boolean.FALSE; - } - } - else if (lc == Integer.class) - { - if (rc == Long.class) - { - lv = ((Number) lv).longValue(); - } - else if (rc == Float.class) - { - lv = ((Number) lv).floatValue(); - } - else if (rc == Double.class) - { - lv = ((Number) lv).doubleValue(); - } - else - { - return Boolean.FALSE; - } - } - else if (lc == Long.class) - { - if (rc == Integer.class) - { - rv = ((Number) rv).longValue(); - } - else if (rc == Float.class) - { - lv = ((Number) lv).floatValue(); - } - else if (rc == Double.class) - { - lv = ((Number) lv).doubleValue(); - } - else - { - return Boolean.FALSE; - } - } - else if (lc == Float.class) - { - if (rc == Integer.class) - { - rv = ((Number) rv).floatValue(); - } - else if (rc == Long.class) - { - rv = ((Number) rv).floatValue(); - } - else if (rc == Double.class) - { - lv = ((Number) lv).doubleValue(); - } - else - { - return Boolean.FALSE; - } - } - else if (lc == Double.class) - { - if (rc == Integer.class) - { - rv = ((Number) rv).doubleValue(); - } - else if (rc == Long.class) - { - rv = ((Number) rv).doubleValue(); - } - else if (rc == Float.class) - { - rv = ((Number) rv).doubleValue(); - } - else - { - return Boolean.FALSE; - } - } - else - { - return Boolean.FALSE; - } - } - - return asBoolean(lv.compareTo(rv)) ? Boolean.TRUE : Boolean.FALSE; - } - - protected abstract boolean asBoolean(int answer); - - public boolean matches(Filterable message) - { - Object object = evaluate(message); - - return (object != null) && (object == Boolean.TRUE); - } - - private static class EqualExpression extends ComparisonExpression - { - public EqualExpression(final Expression left, final Expression right) - { - super(left, right); - } - - public Object evaluate(Filterable message) - { - Object lv = left.evaluate(message); - Object rv = right.evaluate(message); - - // Iff one of the values is null - if ((lv == null) ^ (rv == null)) - { - return Boolean.FALSE; - } - - if ((lv == rv) || lv.equals(rv)) - { - return Boolean.TRUE; - } - - if ((lv instanceof Comparable) && (rv instanceof Comparable)) - { - return compare((Comparable) lv, (Comparable) rv); - } - - return Boolean.FALSE; - } - - protected boolean asBoolean(int answer) - { - return answer == 0; - } - - public String getExpressionSymbol() - { - return "="; - } - } -} diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/ConstantExpression.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/ConstantExpression.java deleted file mode 100644 index 5cc9ca8ef2..0000000000 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/ConstantExpression.java +++ /dev/null @@ -1,209 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.filter; -// -// Based on like named file from r450141 of the Apache ActiveMQ project -// - -import java.math.BigDecimal; - -import org.apache.qpid.server.queue.Filterable; - -/** - * Represents a constant expression - */ -public class ConstantExpression implements Expression -{ - - static class BooleanConstantExpression extends ConstantExpression implements BooleanExpression - { - public BooleanConstantExpression(Object value) - { - super(value); - } - - public boolean matches(Filterable message) - { - Object object = evaluate(message); - - return (object != null) && (object == Boolean.TRUE); - } - } - - public static final BooleanConstantExpression NULL = new BooleanConstantExpression(null); - public static final BooleanConstantExpression TRUE = new BooleanConstantExpression(Boolean.TRUE); - public static final BooleanConstantExpression FALSE = new BooleanConstantExpression(Boolean.FALSE); - - 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); - } - - long l = value.longValue(); - if ((Integer.MIN_VALUE <= l) && (l <= Integer.MAX_VALUE)) - { - value = value.intValue(); - } - - return new ConstantExpression(value); - } - - public static ConstantExpression createFromHex(String text) - { - Number value = Long.parseLong(text.substring(2), 16); - long l = value.longValue(); - if ((Integer.MIN_VALUE <= l) && (l <= Integer.MAX_VALUE)) - { - value = value.intValue(); - } - - return new ConstantExpression(value); - } - - public static ConstantExpression createFromOctal(String text) - { - Number value = Long.parseLong(text, 8); - long l = value.longValue(); - if ((Integer.MIN_VALUE <= l) && (l <= Integer.MAX_VALUE)) - { - value = value.intValue(); - } - - return new ConstantExpression(value); - } - - public static ConstantExpression createFloat(String text) - { - Number value = new Double(text); - - return new ConstantExpression(value); - } - - public ConstantExpression(Object value) - { - this.value = value; - } - - public Object evaluate(Filterable message) - { - return value; - } - - public Object getValue() - { - return value; - } - - /** - * @see java.lang.Object#toString() - */ - public String toString() - { - if (value == null) - { - return "NULL"; - } - - if (value instanceof Boolean) - { - return ((Boolean) value) ? "TRUE" : "FALSE"; - } - - if (value instanceof String) - { - return encodeString((String) value); - } - - return value.toString(); - } - - /** - * TODO: more efficient hashCode() - * - * @see java.lang.Object#hashCode() - */ - public int hashCode() - { - return toString().hashCode(); - } - - /** - * TODO: more efficient hashCode() - * - * @see java.lang.Object#equals(java.lang.Object) - */ - public boolean equals(Object o) - { - - if ((o == null) || !this.getClass().equals(o.getClass())) - { - return false; - } - - return toString().equals(o.toString()); - - } - - /** - * Encodes the value of string so that it looks like it would look like - * when it was provided in a selector. - * - * @param s - * @return - */ - public static String encodeString(String s) - { - StringBuffer b = new StringBuffer(); - b.append('\''); - for (int i = 0; i < s.length(); i++) - { - char c = s.charAt(i); - if (c == '\'') - { - b.append(c); - } - - b.append(c); - } - - b.append('\''); - - return b.toString(); - } - -} diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/Expression.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/Expression.java deleted file mode 100644 index 97e9915271..0000000000 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/Expression.java +++ /dev/null @@ -1,36 +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.filter; -// -// Based on like named file from r450141 of the Apache ActiveMQ project -// - -import org.apache.qpid.server.queue.Filterable; - -/** - * Represents an expression - */ -public interface Expression -{ - - /** - * @return the value of this expression - */ - public Object evaluate(Filterable message); - -} diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/FilterManagerFactory.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/FilterManagerFactory.java index dac517150a..56f0a6e08d 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/FilterManagerFactory.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/FilterManagerFactory.java @@ -20,12 +20,17 @@ */ package org.apache.qpid.server.filter; -import java.util.Map; +import org.apache.log4j.Logger; import org.apache.qpid.AMQException; +import org.apache.qpid.AMQInvalidArgumentException; import org.apache.qpid.common.AMQPFilterTypes; +import org.apache.qpid.filter.SelectorParsingException; +import org.apache.qpid.filter.selector.ParseException; +import org.apache.qpid.filter.selector.TokenMgrError; import org.apache.qpid.framing.FieldTable; -import org.apache.log4j.Logger; + +import java.util.Map; public class FilterManagerFactory @@ -33,6 +38,10 @@ public class FilterManagerFactory private final static Logger _logger = Logger.getLogger(FilterManagerFactory.class); + private FilterManagerFactory() + { + } + //fixme move to a common class so it can be refered to from client code. public static FilterManager createManager(FieldTable filters) throws AMQException @@ -51,7 +60,22 @@ public class FilterManagerFactory if (selector != null && !selector.equals("")) { manager = new SimpleFilterManager(); - manager.add(new JMSSelectorFilter(selector)); + try + { + manager.add(new JMSSelectorFilter(selector)); + } + catch (ParseException e) + { + throw new AMQInvalidArgumentException("Cannot parse JMS selector \"" + selector + "\"", e); + } + catch (SelectorParsingException e) + { + throw new AMQInvalidArgumentException("Cannot parse JMS selector \"" + selector + "\"", e); + } + catch (TokenMgrError e) + { + throw new AMQInvalidArgumentException("Cannot parse JMS selector \"" + selector + "\"", e); + } } } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/JMSSelectorFilter.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/JMSSelectorFilter.java index 423bbc244e..47cacdc176 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/JMSSelectorFilter.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/JMSSelectorFilter.java @@ -21,8 +21,13 @@ package org.apache.qpid.server.filter; import org.apache.log4j.Logger; -import org.apache.qpid.AMQInvalidArgumentException; -import org.apache.qpid.server.filter.jms.selector.SelectorParser; + +import org.apache.qpid.filter.BooleanExpression; +import org.apache.qpid.filter.FilterableMessage; +import org.apache.qpid.filter.SelectorParsingException; +import org.apache.qpid.filter.selector.ParseException; +import org.apache.qpid.filter.selector.SelectorParser; +import org.apache.qpid.filter.selector.TokenMgrError; import org.apache.qpid.server.queue.Filterable; @@ -33,7 +38,7 @@ public class JMSSelectorFilter implements MessageFilter private String _selector; private BooleanExpression _matcher; - public JMSSelectorFilter(String selector) throws AMQInvalidArgumentException + public JMSSelectorFilter(String selector) throws ParseException, TokenMgrError, SelectorParsingException { _selector = selector; _matcher = new SelectorParser().parse(selector); @@ -41,7 +46,8 @@ public class JMSSelectorFilter implements MessageFilter public boolean matches(Filterable message) { - boolean match = _matcher.matches(message); + + boolean match = _matcher.matches(wrap(message)); if(_logger.isDebugEnabled()) { _logger.debug(message + " match(" + match + ") selector(" + System.identityHashCode(_selector) + "):" + _selector); @@ -49,6 +55,62 @@ public class JMSSelectorFilter implements MessageFilter return match; } + private FilterableMessage wrap(final Filterable message) + { + return new FilterableMessage() + { + public boolean isPersistent() + { + return message.isPersistent(); + } + + public boolean isRedelivered() + { + return message.isRedelivered(); + } + + public Object getHeader(String name) + { + return message.getMessageHeader().getHeader(name); + } + + public String getReplyTo() + { + return message.getMessageHeader().getReplyTo(); + } + + public String getType() + { + return message.getMessageHeader().getType(); + } + + public byte getPriority() + { + return message.getMessageHeader().getPriority(); + } + + public String getMessageId() + { + return message.getMessageHeader().getMessageId(); + } + + public long getTimestamp() + { + return message.getMessageHeader().getTimestamp(); + } + + public String getCorrelationId() + { + return message.getMessageHeader().getCorrelationId(); + } + + public long getExpiration() + { + return message.getMessageHeader().getExpiration(); + } + }; + } + public String getSelector() { return _selector; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/LogicExpression.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/LogicExpression.java deleted file mode 100644 index fdba184da4..0000000000 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/LogicExpression.java +++ /dev/null @@ -1,120 +0,0 @@ -/** - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.qpid.server.filter; -// -// Based on like named file from r450141 of the Apache ActiveMQ project -// - -import org.apache.qpid.server.queue.Filterable; - -/** - * A filter performing a comparison of two objects - */ -public abstract class LogicExpression extends BinaryExpression implements BooleanExpression -{ - - public static BooleanExpression createOR(BooleanExpression lvalue, BooleanExpression rvalue) - { - return new OrExpression(lvalue, rvalue); - } - - public static BooleanExpression createAND(BooleanExpression lvalue, BooleanExpression rvalue) - { - return new AndExpression(lvalue, rvalue); - } - - /** - * @param left - * @param right - */ - public LogicExpression(BooleanExpression left, BooleanExpression right) - { - super(left, right); - } - - public abstract Object evaluate(Filterable message); - - public boolean matches(Filterable message) - { - Object object = evaluate(message); - - return (object != null) && (object == Boolean.TRUE); - } - - private static class OrExpression extends LogicExpression - { - public OrExpression(final BooleanExpression lvalue, final BooleanExpression rvalue) - { - super(lvalue, rvalue); - } - - public Object evaluate(Filterable message) - { - - Boolean lv = (Boolean) left.evaluate(message); - // Can we do an OR shortcut?? - if ((lv != null) && lv.booleanValue()) - { - return Boolean.TRUE; - } - - Boolean rv = (Boolean) right.evaluate(message); - - return (rv == null) ? null : rv; - } - - public String getExpressionSymbol() - { - return "OR"; - } - } - - private static class AndExpression extends LogicExpression - { - public AndExpression(final BooleanExpression lvalue, final BooleanExpression rvalue) - { - super(lvalue, rvalue); - } - - public Object evaluate(Filterable message) - { - - Boolean lv = (Boolean) left.evaluate(message); - - // Can we do an AND shortcut?? - if (lv == null) - { - return null; - } - - if (!lv.booleanValue()) - { - return Boolean.FALSE; - } - - Boolean rv = (Boolean) right.evaluate(message); - - return (rv == null) ? null : rv; - } - - public String getExpressionSymbol() - { - return "AND"; - } - } -} diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/NoConsumerFilter.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/NoConsumerFilter.java index 65ddf19fc4..d3e097d22c 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/NoConsumerFilter.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/NoConsumerFilter.java @@ -21,6 +21,7 @@ package org.apache.qpid.server.filter; import org.apache.log4j.Logger; + import org.apache.qpid.AMQException; import org.apache.qpid.server.queue.Filterable; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/PropertyExpression.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/PropertyExpression.java deleted file mode 100644 index 9848f90ea9..0000000000 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/PropertyExpression.java +++ /dev/null @@ -1,236 +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.filter; -// -// Based on like named file from r450141 of the Apache ActiveMQ project -// - -import java.util.HashMap; - -import org.apache.log4j.Logger; - -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.CommonContentHeaderProperties; -import org.apache.qpid.server.queue.Filterable; - -/** - * Represents a property expression - */ -public class PropertyExpression implements Expression -{ - // Constants - defined the same as JMS - private static enum JMSDeliveryMode { NON_PERSISTENT, PERSISTENT } - - private static final int DEFAULT_PRIORITY = 4; - - private static final Logger _logger = org.apache.log4j.Logger.getLogger(PropertyExpression.class); - - private static final HashMap JMS_PROPERTY_EXPRESSIONS = new HashMap(); - - { - JMS_PROPERTY_EXPRESSIONS.put("JMSDestination", new Expression() - { - public Object evaluate(Filterable message) - { - //TODO - return null; - } - }); - JMS_PROPERTY_EXPRESSIONS.put("JMSReplyTo", new ReplyToExpression()); - - JMS_PROPERTY_EXPRESSIONS.put("JMSType", new TypeExpression()); - - JMS_PROPERTY_EXPRESSIONS.put("JMSDeliveryMode", new DeliveryModeExpression()); - - JMS_PROPERTY_EXPRESSIONS.put("JMSPriority", new PriorityExpression()); - - JMS_PROPERTY_EXPRESSIONS.put("JMSMessageID", new MessageIDExpression()); - - JMS_PROPERTY_EXPRESSIONS.put("AMQMessageID", new MessageIDExpression()); - - JMS_PROPERTY_EXPRESSIONS.put("JMSTimestamp", new TimestampExpression()); - - JMS_PROPERTY_EXPRESSIONS.put("JMSCorrelationID", new CorrelationIdExpression()); - - JMS_PROPERTY_EXPRESSIONS.put("JMSExpiration", new ExpirationExpression()); - - JMS_PROPERTY_EXPRESSIONS.put("JMSRedelivered", new Expression() - { - public Object evaluate(Filterable message) - { - return message.isRedelivered(); - } - }); - } - - private final String name; - private final Expression jmsPropertyExpression; - - public boolean outerTest() - { - return false; - } - - public PropertyExpression(String name) - { - this.name = name; - - - - jmsPropertyExpression = (Expression) JMS_PROPERTY_EXPRESSIONS.get(name); - } - - public Object evaluate(Filterable message) - { - - if (jmsPropertyExpression != null) - { - return jmsPropertyExpression.evaluate(message); - } - else - { - return message.getMessageHeader().getHeader(name); - } - } - - public String getName() - { - return name; - } - - /** - * @see java.lang.Object#toString() - */ - public String toString() - { - return name; - } - - /** - * @see java.lang.Object#hashCode() - */ - public int hashCode() - { - return name.hashCode(); - } - - /** - * @see java.lang.Object#equals(java.lang.Object) - */ - public boolean equals(Object o) - { - - if ((o == null) || !this.getClass().equals(o.getClass())) - { - return false; - } - - return name.equals(((PropertyExpression) o).name); - - } - - private static class ReplyToExpression implements Expression - { - public Object evaluate(Filterable message) - { - String replyTo = message.getMessageHeader().getReplyTo(); - return replyTo; - } - - } - - private static class TypeExpression implements Expression - { - public Object evaluate(Filterable message) - { - - String type = message.getMessageHeader().getType(); - return type; - - } - } - - private static class DeliveryModeExpression implements Expression - { - public Object evaluate(Filterable message) - { - JMSDeliveryMode mode = message.isPersistent() ? JMSDeliveryMode.PERSISTENT : - JMSDeliveryMode.NON_PERSISTENT; - if (_logger.isDebugEnabled()) - { - _logger.debug("JMSDeliveryMode is :" + mode); - } - - return mode.toString(); - } - } - - private static class PriorityExpression implements Expression - { - public Object evaluate(Filterable message) - { - byte priority = message.getMessageHeader().getPriority(); - return (int) priority; - } - } - - private static class MessageIDExpression implements Expression - { - public Object evaluate(Filterable message) - { - - String messageId = message.getMessageHeader().getMessageId(); - - return messageId; - - } - } - - private static class TimestampExpression implements Expression - { - public Object evaluate(Filterable message) - { - long timestamp = message.getMessageHeader().getTimestamp(); - return timestamp; - } - } - - private static class CorrelationIdExpression implements Expression - { - public Object evaluate(Filterable message) - { - - String correlationId = message.getMessageHeader().getCorrelationId(); - - return correlationId; - } - } - - private static class ExpirationExpression implements Expression - { - public Object evaluate(Filterable message) - { - long expiration = message.getMessageHeader().getExpiration(); - return expiration; - - } - } -} diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/SimpleFilterManager.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/SimpleFilterManager.java index 360a5d45ce..b2a9009d23 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/SimpleFilterManager.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/SimpleFilterManager.java @@ -20,12 +20,12 @@ */ package org.apache.qpid.server.filter; -import java.util.concurrent.ConcurrentLinkedQueue; - import org.apache.log4j.Logger; -import org.apache.qpid.AMQException; + import org.apache.qpid.server.queue.Filterable; +import java.util.concurrent.ConcurrentLinkedQueue; + public class SimpleFilterManager implements FilterManager { private final Logger _logger = Logger.getLogger(SimpleFilterManager.class); diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/UnaryExpression.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/UnaryExpression.java deleted file mode 100644 index 557af95001..0000000000 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/UnaryExpression.java +++ /dev/null @@ -1,362 +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.filter; -// -// Based on like named file from r450141 of the Apache ActiveMQ project -// - -import java.math.BigDecimal; -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; - -import org.apache.qpid.AMQException; -import org.apache.qpid.server.queue.Filterable; - -/** - * An expression which performs an operation on two expression values - */ -public abstract class UnaryExpression implements Expression -{ - - private static final BigDecimal BD_LONG_MIN_VALUE = BigDecimal.valueOf(Long.MIN_VALUE); - protected Expression right; - - public static Expression createNegate(Expression left) - { - return new NegativeExpression(left); - } - - public static BooleanExpression createInExpression(PropertyExpression right, List elements, final boolean not) - { - - // Use a HashSet if there are many elements. - Collection t; - if (elements.size() == 0) - { - t = null; - } - else if (elements.size() < 5) - { - t = elements; - } - else - { - t = new HashSet(elements); - } - - final Collection inList = t; - - return new InExpression(right, inList, not); - } - - abstract static class BooleanUnaryExpression extends UnaryExpression implements BooleanExpression - { - public BooleanUnaryExpression(Expression left) - { - super(left); - } - - public boolean matches(Filterable message) - { - Object object = evaluate(message); - - return (object != null) && (object == Boolean.TRUE); - } - } - ; - - public static BooleanExpression createNOT(BooleanExpression left) - { - return new NotExpression(left); - } - - public static BooleanExpression createXPath(final String xpath) - { - return new XPathExpression(xpath); - } - - public static BooleanExpression createXQuery(final String xpath) - { - return new XQueryExpression(xpath); - } - - public static BooleanExpression createBooleanCast(Expression left) - { - return new BooleanCastExpression(left); - } - - private static Number negate(Number left) - { - Class clazz = left.getClass(); - if (clazz == Integer.class) - { - return -left.intValue(); - } - else if (clazz == Long.class) - { - return -left.longValue(); - } - else if (clazz == Float.class) - { - return -left.floatValue(); - } - else if (clazz == Double.class) - { - return -left.doubleValue(); - } - else if (clazz == BigDecimal.class) - { - // We ussually get a big deciamal when we have Long.MIN_VALUE constant in the - // Selector. Long.MIN_VALUE is too big to store in a Long as a positive so we store it - // as a Big decimal. But it gets Negated right away.. to here we try to covert it back - // to a Long. - BigDecimal bd = (BigDecimal) left; - bd = bd.negate(); - - if (BD_LONG_MIN_VALUE.compareTo(bd) == 0) - { - return Long.MIN_VALUE; - } - - return bd; - } - else - { - throw new RuntimeException("Don't know how to negate: " + left); - } - } - - public UnaryExpression(Expression left) - { - this.right = left; - } - - public Expression getRight() - { - return right; - } - - public void setRight(Expression expression) - { - right = expression; - } - - /** - * @see java.lang.Object#toString() - */ - public String toString() - { - return "(" + getExpressionSymbol() + " " + right.toString() + ")"; - } - - /** - * TODO: more efficient hashCode() - * - * @see java.lang.Object#hashCode() - */ - public int hashCode() - { - return toString().hashCode(); - } - - /** - * TODO: more efficient hashCode() - * - * @see java.lang.Object#equals(java.lang.Object) - */ - public boolean equals(Object o) - { - return ((o != null) && this.getClass().equals(o.getClass())) && toString().equals(o.toString()); - } - - /** - * Returns the symbol that represents this binary expression. For example, addition is - * represented by "+" - * - * @return - */ - public abstract String getExpressionSymbol(); - - private static class NegativeExpression extends UnaryExpression - { - public NegativeExpression(final Expression left) - { - super(left); - } - - public Object evaluate(Filterable message) - { - Object rvalue = right.evaluate(message); - if (rvalue == null) - { - return null; - } - - if (rvalue instanceof Number) - { - return negate((Number) rvalue); - } - - return null; - } - - public String getExpressionSymbol() - { - return "-"; - } - } - - private static class InExpression extends BooleanUnaryExpression - { - private final Collection _inList; - private final boolean _not; - - public InExpression(final PropertyExpression right, final Collection inList, final boolean not) - { - super(right); - _inList = inList; - _not = not; - } - - public Object evaluate(Filterable message) - { - - Object rvalue = right.evaluate(message); - if (rvalue == null) - { - return null; - } - - if (rvalue.getClass() != String.class) - { - return null; - } - - if (((_inList != null) && _inList.contains(rvalue)) ^ _not) - { - return Boolean.TRUE; - } - else - { - return Boolean.FALSE; - } - - } - - public String toString() - { - StringBuffer answer = new StringBuffer(); - answer.append(right); - answer.append(" "); - answer.append(getExpressionSymbol()); - answer.append(" ( "); - - int count = 0; - for (Iterator i = _inList.iterator(); i.hasNext();) - { - Object o = (Object) i.next(); - if (count != 0) - { - answer.append(", "); - } - - answer.append(o); - count++; - } - - answer.append(" )"); - - return answer.toString(); - } - - public String getExpressionSymbol() - { - if (_not) - { - return "NOT IN"; - } - else - { - return "IN"; - } - } - } - - private static class NotExpression extends BooleanUnaryExpression - { - public NotExpression(final BooleanExpression left) - { - super(left); - } - - public Object evaluate(Filterable message) - { - Boolean lvalue = (Boolean) right.evaluate(message); - if (lvalue == null) - { - return null; - } - - return lvalue.booleanValue() ? Boolean.FALSE : Boolean.TRUE; - } - - public String getExpressionSymbol() - { - return "NOT"; - } - } - - private static class BooleanCastExpression extends BooleanUnaryExpression - { - public BooleanCastExpression(final Expression left) - { - super(left); - } - - public Object evaluate(Filterable message) - { - Object rvalue = right.evaluate(message); - if (rvalue == null) - { - return null; - } - - if (!rvalue.getClass().equals(Boolean.class)) - { - return Boolean.FALSE; - } - - return ((Boolean) rvalue).booleanValue() ? Boolean.TRUE : Boolean.FALSE; - } - - public String toString() - { - return right.toString(); - } - - public String getExpressionSymbol() - { - return ""; - } - } -} diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/XPathExpression.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/XPathExpression.java deleted file mode 100644 index aa35cb5a76..0000000000 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/XPathExpression.java +++ /dev/null @@ -1,126 +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.filter; -// -// Based on like named file from r450141 of the Apache ActiveMQ project -// - -import org.apache.log4j.Logger; -import org.apache.qpid.AMQException; -import org.apache.qpid.server.queue.Filterable; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; - -/** - * Used to evaluate an XPath Expression in a JMS selector. - */ -public final class XPathExpression implements BooleanExpression { - - private static final Logger log = Logger.getLogger(XPathExpression.class); - private static final String EVALUATOR_SYSTEM_PROPERTY = "org.apache.qpid.server.filter.XPathEvaluatorClassName"; - private static final String DEFAULT_EVALUATOR_CLASS_NAME=XalanXPathEvaluator.class.getName(); - - private static final Constructor EVALUATOR_CONSTRUCTOR; - - static { - String cn = System.getProperty(EVALUATOR_SYSTEM_PROPERTY, DEFAULT_EVALUATOR_CLASS_NAME); - Constructor m = null; - try { - try { - m = getXPathEvaluatorConstructor(cn); - } catch (Throwable e) { - log.warn("Invalid "+XPathEvaluator.class.getName()+" implementation: "+cn+", reason: "+e,e); - cn = DEFAULT_EVALUATOR_CLASS_NAME; - try { - m = getXPathEvaluatorConstructor(cn); - } catch (Throwable e2) { - log.error("Default XPath evaluator could not be loaded",e); - } - } - } finally { - EVALUATOR_CONSTRUCTOR = m; - } - } - - private static Constructor getXPathEvaluatorConstructor(String cn) throws ClassNotFoundException, SecurityException, NoSuchMethodException { - Class c = XPathExpression.class.getClassLoader().loadClass(cn); - if( !XPathEvaluator.class.isAssignableFrom(c) ) { - throw new ClassCastException(""+c+" is not an instance of "+XPathEvaluator.class); - } - return c.getConstructor(new Class[]{String.class}); - } - - private final String xpath; - private final XPathEvaluator evaluator; - - static public interface XPathEvaluator { - public boolean evaluate(Filterable message); - } - - XPathExpression(String xpath) { - this.xpath = xpath; - this.evaluator = createEvaluator(xpath); - } - - private XPathEvaluator createEvaluator(String xpath2) { - try { - return (XPathEvaluator)EVALUATOR_CONSTRUCTOR.newInstance(new Object[]{xpath}); - } catch (InvocationTargetException e) { - Throwable cause = e.getCause(); - if( cause instanceof RuntimeException ) { - throw (RuntimeException)cause; - } - throw new RuntimeException("Invalid XPath Expression: "+xpath+" reason: "+e.getMessage(), e); - } catch (Throwable e) { - throw new RuntimeException("Invalid XPath Expression: "+xpath+" reason: "+e.getMessage(), e); - } - } - - public Object evaluate(Filterable message) { -// try { -//FIXME this is flow to disk work -// if( message.isDropped() ) -// return null; - return evaluator.evaluate(message) ? Boolean.TRUE : Boolean.FALSE; -// } catch (IOException e) { -// -// JMSException exception = new JMSException(e.getMessage()); -// exception.initCause(e); -// throw exception; -// -// } - - } - - public String toString() { - return "XPATH "+ConstantExpression.encodeString(xpath); - } - - /** - * @param message - * @return true if the expression evaluates to Boolean.TRUE. - * @throws AMQException - */ - public boolean matches(Filterable message) - { - Object object = evaluate(message); - return object!=null && object==Boolean.TRUE; - } - -} diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/XQueryExpression.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/XQueryExpression.java deleted file mode 100644 index ae22f17413..0000000000 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/XQueryExpression.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.qpid.server.filter; - -import org.apache.qpid.AMQException; -import org.apache.qpid.server.queue.Filterable; - -// -// Based on like named file from r450141 of the Apache ActiveMQ project -// - -/** - * Used to evaluate an XQuery Expression in a JMS selector. - */ -public final class XQueryExpression implements BooleanExpression { - private final String xpath; - - XQueryExpression(String xpath) { - super(); - this.xpath = xpath; - } - - public Object evaluate(Filterable message) { - return Boolean.FALSE; - } - - public String toString() { - return "XQUERY "+ConstantExpression.encodeString(xpath); - } - - /** - * @param message - * @return true if the expression evaluates to Boolean.TRUE. - * @throws AMQException - */ - public boolean matches(Filterable message) - { - Object object = evaluate(message); - return object!=null && object==Boolean.TRUE; - } - -} diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/XalanXPathEvaluator.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/XalanXPathEvaluator.java deleted file mode 100644 index f83eb63ac5..0000000000 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/filter/XalanXPathEvaluator.java +++ /dev/null @@ -1,101 +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.filter; -// -// Based on like named file from r450141 of the Apache ActiveMQ project -// - -import java.io.ByteArrayInputStream; -import java.io.StringReader; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; - -import org.apache.qpid.server.queue.Filterable; -import org.apache.xpath.CachedXPathAPI; -import org.w3c.dom.Document; -import org.w3c.dom.traversal.NodeIterator; -import org.xml.sax.InputSource; - -public class XalanXPathEvaluator implements XPathExpression.XPathEvaluator { - - private final String xpath; - - public XalanXPathEvaluator(String xpath) { - this.xpath = xpath; - } - - public boolean evaluate(Filterable m) - { - // 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); - } 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) { - try { - - InputSource inputSource = new InputSource(new ByteArrayInputStream(data)); - - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setNamespaceAware(true); - DocumentBuilder dbuilder = factory.newDocumentBuilder(); - Document doc = dbuilder.parse(inputSource); - - CachedXPathAPI cachedXPathAPI = new CachedXPathAPI(); - NodeIterator iterator = cachedXPathAPI.selectNodeIterator(doc,xpath); - return iterator.nextNode()!=null; - - } catch (Throwable e) { - return false; - } - } - - private boolean evaluate(String text) { - try { - InputSource inputSource = new InputSource(new StringReader(text)); - - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setNamespaceAware(true); - DocumentBuilder dbuilder = factory.newDocumentBuilder(); - Document doc = dbuilder.parse(inputSource); - - // We should associated the cachedXPathAPI object with the message being evaluated - // since that should speedup subsequent xpath expressions. - CachedXPathAPI cachedXPathAPI = new CachedXPathAPI(); - NodeIterator iterator = cachedXPathAPI.selectNodeIterator(doc,xpath); - return iterator.nextNode()!=null; - } catch (Throwable e) { - return false; - } - } -} diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/flow/AbstractFlowCreditManager.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/flow/AbstractFlowCreditManager.java index a77ed5700a..124fb0d1d9 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/flow/AbstractFlowCreditManager.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/flow/AbstractFlowCreditManager.java @@ -22,12 +22,10 @@ package org.apache.qpid.server.flow; import java.util.ArrayList; import java.util.concurrent.atomic.AtomicBoolean; -import java.util.Set; -import java.util.HashSet; public abstract class AbstractFlowCreditManager implements FlowCreditManager { - protected final AtomicBoolean _suspended = new AtomicBoolean(false); + private final AtomicBoolean _suspended = new AtomicBoolean(false); private final ArrayList _listeners = new ArrayList(); public final void addStateListener(FlowCreditManagerListener listener) diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/flow/CreditCreditManager.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/flow/CreditCreditManager.java index c6771177ac..09fe44338c 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/flow/CreditCreditManager.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/flow/CreditCreditManager.java @@ -23,14 +23,8 @@ package org.apache.qpid.server.flow; public class CreditCreditManager extends AbstractFlowCreditManager implements FlowCreditManager_0_10 { - private volatile long _bytesCredit; - private volatile long _messageCredit; - - - public CreditCreditManager() - { - this(0L, 0L); - } + private volatile long _bytesCredit; + private volatile long _messageCredit; public CreditCreditManager(long bytesCredit, long messageCredit) { @@ -67,9 +61,6 @@ public class CreditCreditManager extends AbstractFlowCreditManager implements Fl public synchronized void restoreCredit(final long messageCredit, final long bytesCredit) { - /*_bytesCredit = 0l; - _messageCredit = 0l; - setSuspended(true);*/ } @@ -138,7 +129,6 @@ public class CreditCreditManager extends AbstractFlowCreditManager implements Fl } else { - //setSuspended(true); return false; } } @@ -158,7 +148,6 @@ public class CreditCreditManager extends AbstractFlowCreditManager implements Fl } else { - //setSuspended(true); return false; } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/flow/Pre0_10CreditManager.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/flow/Pre0_10CreditManager.java index a193f8fae4..fc2d4bfb53 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/flow/Pre0_10CreditManager.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/flow/Pre0_10CreditManager.java @@ -155,7 +155,6 @@ public class Pre0_10CreditManager extends AbstractFlowCreditManager implements F } else { - //setSuspended(true); return false; } } @@ -183,7 +182,6 @@ public class Pre0_10CreditManager extends AbstractFlowCreditManager implements F } else { - //setSuspended(true); return false; } } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/flow/WindowCreditManager.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/flow/WindowCreditManager.java index a0c2e9f977..2215c7bb3d 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/flow/WindowCreditManager.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/flow/WindowCreditManager.java @@ -144,7 +144,6 @@ public class WindowCreditManager extends AbstractFlowCreditManager implements Fl } else { - //setSuspended(true); return false; } } @@ -164,7 +163,6 @@ public class WindowCreditManager extends AbstractFlowCreditManager implements Fl } else { - //setSuspended(true); return false; } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/AccessRequestHandler.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/AccessRequestHandler.java index 1b0168df56..e1c2782dec 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/AccessRequestHandler.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/AccessRequestHandler.java @@ -21,15 +21,17 @@ package org.apache.qpid.server.handler; */ -import org.apache.qpid.framing.*; -import org.apache.qpid.framing.amqp_8_0.MethodRegistry_8_0; +import org.apache.qpid.AMQException; +import org.apache.qpid.framing.AccessRequestBody; +import org.apache.qpid.framing.AccessRequestOkBody; +import org.apache.qpid.framing.MethodRegistry; import org.apache.qpid.framing.amqp_0_9.MethodRegistry_0_9; +import org.apache.qpid.framing.amqp_8_0.MethodRegistry_8_0; +import org.apache.qpid.protocol.AMQConstant; import org.apache.qpid.server.AMQChannel; -import org.apache.qpid.server.state.StateAwareMethodListener; -import org.apache.qpid.server.state.AMQStateManager; import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.AMQException; -import org.apache.qpid.protocol.AMQConstant; +import org.apache.qpid.server.state.AMQStateManager; +import org.apache.qpid.server.state.StateAwareMethodListener; /** * @author Apache Software Foundation diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/BasicAckMethodHandler.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/BasicAckMethodHandler.java index f90e7c3dff..398a3ff58a 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/BasicAckMethodHandler.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/BasicAckMethodHandler.java @@ -21,9 +21,9 @@ package org.apache.qpid.server.handler; import org.apache.log4j.Logger; + import org.apache.qpid.AMQException; import org.apache.qpid.framing.BasicAckBody; -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; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/BasicCancelMethodHandler.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/BasicCancelMethodHandler.java index bc2a2dca04..0741385d42 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/BasicCancelMethodHandler.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/BasicCancelMethodHandler.java @@ -20,6 +20,8 @@ */ package org.apache.qpid.server.handler; +import org.apache.log4j.Logger; + import org.apache.qpid.AMQException; import org.apache.qpid.framing.BasicCancelBody; import org.apache.qpid.framing.BasicCancelOkBody; @@ -28,7 +30,6 @@ 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 BasicCancelMethodHandler implements StateAwareMethodListener { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/BasicConsumeMethodHandler.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/BasicConsumeMethodHandler.java index a1cfb14753..514829625d 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/BasicConsumeMethodHandler.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/BasicConsumeMethodHandler.java @@ -21,8 +21,12 @@ package org.apache.qpid.server.handler; import org.apache.log4j.Logger; + import org.apache.qpid.AMQException; -import org.apache.qpid.framing.*; +import org.apache.qpid.framing.AMQMethodBody; +import org.apache.qpid.framing.AMQShortString; +import org.apache.qpid.framing.BasicConsumeBody; +import org.apache.qpid.framing.MethodRegistry; import org.apache.qpid.protocol.AMQConstant; import org.apache.qpid.server.AMQChannel; import org.apache.qpid.server.protocol.AMQProtocolSession; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/BasicGetMethodHandler.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/BasicGetMethodHandler.java index 2073299467..191643493e 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/BasicGetMethodHandler.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/BasicGetMethodHandler.java @@ -22,28 +22,26 @@ package org.apache.qpid.server.handler; import org.apache.log4j.Logger; + import org.apache.qpid.AMQException; import org.apache.qpid.framing.BasicGetBody; import org.apache.qpid.framing.BasicGetEmptyBody; import org.apache.qpid.framing.MethodRegistry; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.FieldTable; import org.apache.qpid.protocol.AMQConstant; import org.apache.qpid.server.AMQChannel; -import org.apache.qpid.server.message.AMQMessage; import org.apache.qpid.server.flow.FlowCreditManager; import org.apache.qpid.server.flow.MessageOnlyCreditManager; -import org.apache.qpid.server.subscription.SubscriptionImpl; -import org.apache.qpid.server.subscription.ClientDeliveryMethod; -import org.apache.qpid.server.subscription.RecordDeliveryMethod; -import org.apache.qpid.server.subscription.Subscription; -import org.apache.qpid.server.subscription.SubscriptionFactoryImpl; +import org.apache.qpid.server.message.AMQMessage; import org.apache.qpid.server.protocol.AMQProtocolSession; import org.apache.qpid.server.protocol.AMQSessionModel; import org.apache.qpid.server.queue.AMQQueue; import org.apache.qpid.server.queue.QueueEntry; import org.apache.qpid.server.state.AMQStateManager; import org.apache.qpid.server.state.StateAwareMethodListener; +import org.apache.qpid.server.subscription.ClientDeliveryMethod; +import org.apache.qpid.server.subscription.RecordDeliveryMethod; +import org.apache.qpid.server.subscription.Subscription; +import org.apache.qpid.server.subscription.SubscriptionFactoryImpl; import org.apache.qpid.server.virtualhost.VirtualHost; public class BasicGetMethodHandler implements StateAwareMethodListener diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/BasicPublishMethodHandler.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/BasicPublishMethodHandler.java index 8f23b1c4d4..cb8918e847 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/BasicPublishMethodHandler.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/BasicPublishMethodHandler.java @@ -21,6 +21,7 @@ package org.apache.qpid.server.handler; import org.apache.log4j.Logger; + import org.apache.qpid.AMQException; import org.apache.qpid.exchange.ExchangeDefaults; import org.apache.qpid.framing.AMQShortString; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/BasicQosHandler.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/BasicQosHandler.java index 2cf043dd26..87a3d1c210 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/BasicQosHandler.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/BasicQosHandler.java @@ -21,13 +21,13 @@ package org.apache.qpid.server.handler; import org.apache.qpid.AMQException; +import org.apache.qpid.framing.AMQMethodBody; import org.apache.qpid.framing.BasicQosBody; import org.apache.qpid.framing.MethodRegistry; -import org.apache.qpid.framing.AMQMethodBody; +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.qpid.server.AMQChannel; public class BasicQosHandler implements StateAwareMethodListener { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/BasicRecoverMethodHandler.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/BasicRecoverMethodHandler.java index 429217321c..0c4c9cac47 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/BasicRecoverMethodHandler.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/BasicRecoverMethodHandler.java @@ -21,13 +21,12 @@ 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.BasicRecoverBody; -import org.apache.qpid.framing.BasicRecoverOkBody; import org.apache.qpid.framing.ProtocolVersion; -import org.apache.qpid.framing.AMQMethodBody; import org.apache.qpid.framing.amqp_8_0.MethodRegistry_8_0; -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; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/BasicRecoverSyncMethodHandler.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/BasicRecoverSyncMethodHandler.java index 1e2a83b922..1e0c0273df 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/BasicRecoverSyncMethodHandler.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/BasicRecoverSyncMethodHandler.java @@ -23,18 +23,16 @@ package org.apache.qpid.server.handler; import org.apache.log4j.Logger; -import org.apache.qpid.framing.BasicRecoverBody; -import org.apache.qpid.framing.ProtocolVersion; +import org.apache.qpid.AMQException; import org.apache.qpid.framing.AMQMethodBody; import org.apache.qpid.framing.BasicRecoverSyncBody; -import org.apache.qpid.framing.amqp_0_91.MethodRegistry_0_91; +import org.apache.qpid.framing.ProtocolVersion; import org.apache.qpid.framing.amqp_0_9.MethodRegistry_0_9; -import org.apache.qpid.framing.amqp_8_0.MethodRegistry_8_0; -import org.apache.qpid.server.state.StateAwareMethodListener; -import org.apache.qpid.server.state.AMQStateManager; -import org.apache.qpid.server.protocol.AMQProtocolSession; +import org.apache.qpid.framing.amqp_0_91.MethodRegistry_0_91; import org.apache.qpid.server.AMQChannel; -import org.apache.qpid.AMQException; +import org.apache.qpid.server.protocol.AMQProtocolSession; +import org.apache.qpid.server.state.AMQStateManager; +import org.apache.qpid.server.state.StateAwareMethodListener; public class BasicRecoverSyncMethodHandler implements StateAwareMethodListener { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/BasicRejectMethodHandler.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/BasicRejectMethodHandler.java index 0ea88e4ab6..de76050898 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/BasicRejectMethodHandler.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/BasicRejectMethodHandler.java @@ -20,14 +20,15 @@ */ package org.apache.qpid.server.handler; +import org.apache.log4j.Logger; + import org.apache.qpid.AMQException; import org.apache.qpid.framing.BasicRejectBody; import org.apache.qpid.server.AMQChannel; -import org.apache.qpid.server.queue.QueueEntry; import org.apache.qpid.server.protocol.AMQProtocolSession; +import org.apache.qpid.server.queue.QueueEntry; import org.apache.qpid.server.state.AMQStateManager; import org.apache.qpid.server.state.StateAwareMethodListener; -import org.apache.log4j.Logger; public class BasicRejectMethodHandler implements StateAwareMethodListener { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelCloseHandler.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelCloseHandler.java index ecffd1b9cb..0c8ab318b2 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelCloseHandler.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelCloseHandler.java @@ -21,17 +21,16 @@ package org.apache.qpid.server.handler; import org.apache.log4j.Logger; + import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQFrame; import org.apache.qpid.framing.ChannelCloseBody; import org.apache.qpid.framing.ChannelCloseOkBody; import org.apache.qpid.framing.MethodRegistry; -import org.apache.qpid.protocol.AMQMethodEvent; import org.apache.qpid.protocol.AMQConstant; +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.qpid.server.AMQChannel; public class ChannelCloseHandler implements StateAwareMethodListener { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelCloseOkHandler.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelCloseOkHandler.java index a857490e7e..54b3f813af 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelCloseOkHandler.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelCloseOkHandler.java @@ -21,9 +21,9 @@ package org.apache.qpid.server.handler; import org.apache.log4j.Logger; + import org.apache.qpid.AMQException; import org.apache.qpid.framing.ChannelCloseOkBody; -import org.apache.qpid.protocol.AMQMethodEvent; import org.apache.qpid.server.state.AMQStateManager; import org.apache.qpid.server.state.StateAwareMethodListener; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelFlowHandler.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelFlowHandler.java index 365c8bd9c6..a736ad5fb0 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelFlowHandler.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelFlowHandler.java @@ -21,9 +21,11 @@ package org.apache.qpid.server.handler; import org.apache.log4j.Logger; + import org.apache.qpid.AMQException; -import org.apache.qpid.framing.*; -import org.apache.qpid.protocol.AMQMethodEvent; +import org.apache.qpid.framing.AMQMethodBody; +import org.apache.qpid.framing.ChannelFlowBody; +import org.apache.qpid.framing.MethodRegistry; import org.apache.qpid.server.AMQChannel; import org.apache.qpid.server.protocol.AMQProtocolSession; import org.apache.qpid.server.state.AMQStateManager; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelOpenHandler.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelOpenHandler.java index 6d874ee971..81734d7825 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelOpenHandler.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ChannelOpenHandler.java @@ -20,12 +20,8 @@ */ package org.apache.qpid.server.handler; -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.util.UUID; - import org.apache.log4j.Logger; + import org.apache.qpid.AMQException; import org.apache.qpid.framing.ChannelOpenBody; import org.apache.qpid.framing.ChannelOpenOkBody; @@ -41,6 +37,11 @@ import org.apache.qpid.server.state.AMQStateManager; import org.apache.qpid.server.state.StateAwareMethodListener; import org.apache.qpid.server.virtualhost.VirtualHost; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.util.UUID; + public class ChannelOpenHandler implements StateAwareMethodListener { private static final Logger _logger = Logger.getLogger(ChannelOpenHandler.class); diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionCloseMethodHandler.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionCloseMethodHandler.java index 6eaba87b79..7f0c0d2974 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionCloseMethodHandler.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionCloseMethodHandler.java @@ -21,12 +21,11 @@ package org.apache.qpid.server.handler; import org.apache.log4j.Logger; + import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQFrame; import org.apache.qpid.framing.ConnectionCloseBody; import org.apache.qpid.framing.ConnectionCloseOkBody; import org.apache.qpid.framing.MethodRegistry; -import org.apache.qpid.protocol.AMQMethodEvent; import org.apache.qpid.server.protocol.AMQProtocolSession; import org.apache.qpid.server.state.AMQStateManager; import org.apache.qpid.server.state.StateAwareMethodListener; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionCloseOkMethodHandler.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionCloseOkMethodHandler.java index bc6e5ab403..bd86c2d3f1 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionCloseOkMethodHandler.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionCloseOkMethodHandler.java @@ -21,9 +21,9 @@ package org.apache.qpid.server.handler; import org.apache.log4j.Logger; + import org.apache.qpid.AMQException; import org.apache.qpid.framing.ConnectionCloseOkBody; -import org.apache.qpid.protocol.AMQMethodEvent; import org.apache.qpid.server.protocol.AMQProtocolSession; import org.apache.qpid.server.state.AMQState; import org.apache.qpid.server.state.AMQStateManager; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionOpenMethodHandler.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionOpenMethodHandler.java index 9a79467526..79fcfb6d76 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionOpenMethodHandler.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionOpenMethodHandler.java @@ -21,6 +21,7 @@ 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.AMQShortString; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionSecureOkMethodHandler.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionSecureOkMethodHandler.java index 09f35da41d..2ccf97f17c 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionSecureOkMethodHandler.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionSecureOkMethodHandler.java @@ -21,9 +21,8 @@ package org.apache.qpid.server.handler; -import javax.security.sasl.SaslException; -import javax.security.sasl.SaslServer; import org.apache.log4j.Logger; + import org.apache.qpid.AMQException; import org.apache.qpid.framing.ConnectionCloseBody; import org.apache.qpid.framing.ConnectionSecureBody; @@ -40,6 +39,9 @@ import org.apache.qpid.server.state.AMQState; import org.apache.qpid.server.state.AMQStateManager; import org.apache.qpid.server.state.StateAwareMethodListener; +import javax.security.sasl.SaslException; +import javax.security.sasl.SaslServer; + public class ConnectionSecureOkMethodHandler implements StateAwareMethodListener { private static final Logger _logger = Logger.getLogger(ConnectionSecureOkMethodHandler.class); diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionStartOkMethodHandler.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionStartOkMethodHandler.java index 2dd9a63540..162e4e0215 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionStartOkMethodHandler.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionStartOkMethodHandler.java @@ -20,10 +20,8 @@ */ package org.apache.qpid.server.handler; -import javax.security.sasl.SaslException; -import javax.security.sasl.SaslServer; - import org.apache.log4j.Logger; + import org.apache.qpid.AMQException; import org.apache.qpid.framing.ConnectionCloseBody; import org.apache.qpid.framing.ConnectionSecureBody; @@ -41,6 +39,9 @@ import org.apache.qpid.server.state.AMQState; import org.apache.qpid.server.state.AMQStateManager; import org.apache.qpid.server.state.StateAwareMethodListener; +import javax.security.sasl.SaslException; +import javax.security.sasl.SaslServer; + public class ConnectionStartOkMethodHandler implements StateAwareMethodListener { @@ -79,10 +80,7 @@ public class ConnectionStartOkMethodHandler implements StateAwareMethodListener< final AuthenticationResult authResult = authMgr.authenticate(ss, body.getResponse()); //save clientProperties - if (session.getClientProperties() == null) - { - session.setClientProperties(body.getClientProperties()); - } + session.setClientProperties(body.getClientProperties()); MethodRegistry methodRegistry = session.getMethodRegistry(); diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionTuneOkMethodHandler.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionTuneOkMethodHandler.java index 1da2760639..299aad0fe7 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionTuneOkMethodHandler.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ConnectionTuneOkMethodHandler.java @@ -21,6 +21,7 @@ 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.server.protocol.AMQProtocolSession; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeBoundHandler.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeBoundHandler.java index 53835f381f..b4eb41684d 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeBoundHandler.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeBoundHandler.java @@ -21,12 +21,15 @@ package org.apache.qpid.server.handler; import org.apache.qpid.AMQException; -import org.apache.qpid.framing.*; +import org.apache.qpid.framing.AMQShortString; +import org.apache.qpid.framing.ExchangeBoundBody; +import org.apache.qpid.framing.ExchangeBoundOkBody; +import org.apache.qpid.framing.MethodRegistry; import org.apache.qpid.server.AMQChannel; import org.apache.qpid.server.exchange.Exchange; import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.queue.QueueRegistry; 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; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeDeclareHandler.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeDeclareHandler.java index 69cf0c9e20..6d55f31ebc 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeDeclareHandler.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ExchangeDeclareHandler.java @@ -21,10 +21,14 @@ package org.apache.qpid.server.handler; import org.apache.log4j.Logger; + import org.apache.qpid.AMQConnectionException; import org.apache.qpid.AMQException; import org.apache.qpid.AMQUnknownExchangeType; -import org.apache.qpid.framing.*; +import org.apache.qpid.framing.AMQMethodBody; +import org.apache.qpid.framing.AMQShortString; +import org.apache.qpid.framing.ExchangeDeclareBody; +import org.apache.qpid.framing.MethodRegistry; import org.apache.qpid.protocol.AMQConstant; import org.apache.qpid.server.AMQChannel; import org.apache.qpid.server.exchange.Exchange; @@ -62,26 +66,39 @@ public class ExchangeDeclareHandler implements StateAwareMethodListener { private static final Logger _logger = Logger.getLogger(QueueDeclareHandler.class); @@ -56,9 +56,7 @@ public class QueueDeclareHandler implements StateAwareMethodListener { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/QueuePurgeHandler.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/QueuePurgeHandler.java index 7d609f9064..217a264793 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/QueuePurgeHandler.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/QueuePurgeHandler.java @@ -22,18 +22,18 @@ package org.apache.qpid.server.handler; import org.apache.qpid.AMQException; -import org.apache.qpid.framing.QueuePurgeBody; -import org.apache.qpid.framing.MethodRegistry; import org.apache.qpid.framing.AMQMethodBody; +import org.apache.qpid.framing.MethodRegistry; +import org.apache.qpid.framing.QueuePurgeBody; import org.apache.qpid.protocol.AMQConstant; +import org.apache.qpid.server.AMQChannel; import org.apache.qpid.server.protocol.AMQProtocolSession; import org.apache.qpid.server.protocol.AMQSessionModel; -import org.apache.qpid.server.queue.QueueRegistry; 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.qpid.server.AMQChannel; public class QueuePurgeHandler implements StateAwareMethodListener { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/QueueUnbindHandler.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/QueueUnbindHandler.java index 9915627a94..a8ae2099cc 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/QueueUnbindHandler.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/QueueUnbindHandler.java @@ -21,6 +21,7 @@ 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.AMQShortString; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ServerMethodDispatcherImpl.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ServerMethodDispatcherImpl.java index e290afcde3..3b6dc3f3f5 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ServerMethodDispatcherImpl.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ServerMethodDispatcherImpl.java @@ -20,12 +20,12 @@ */ package org.apache.qpid.server.handler; -import java.util.Map; -import java.util.HashMap; - -import org.apache.qpid.server.state.AMQStateManager; -import org.apache.qpid.framing.*; import org.apache.qpid.AMQException; +import org.apache.qpid.framing.*; +import org.apache.qpid.server.state.AMQStateManager; + +import java.util.HashMap; +import java.util.Map; public class ServerMethodDispatcherImpl implements MethodDispatcher { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ServerMethodDispatcherImpl_0_9.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ServerMethodDispatcherImpl_0_9.java index 8b1dca77ba..7ce8664d37 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ServerMethodDispatcherImpl_0_9.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ServerMethodDispatcherImpl_0_9.java @@ -21,10 +21,10 @@ package org.apache.qpid.server.handler; -import org.apache.qpid.framing.amqp_0_9.MethodDispatcher_0_9; +import org.apache.qpid.AMQException; import org.apache.qpid.framing.*; +import org.apache.qpid.framing.amqp_0_9.MethodDispatcher_0_9; import org.apache.qpid.server.state.AMQStateManager; -import org.apache.qpid.AMQException; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ServerMethodDispatcherImpl_0_91.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ServerMethodDispatcherImpl_0_91.java index 32cd4c4e9f..126e1484b6 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ServerMethodDispatcherImpl_0_91.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ServerMethodDispatcherImpl_0_91.java @@ -21,10 +21,10 @@ package org.apache.qpid.server.handler; +import org.apache.qpid.AMQException; import org.apache.qpid.framing.*; import org.apache.qpid.framing.amqp_0_91.MethodDispatcher_0_91; import org.apache.qpid.server.state.AMQStateManager; -import org.apache.qpid.AMQException; public class ServerMethodDispatcherImpl_0_91 diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ServerMethodDispatcherImpl_8_0.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ServerMethodDispatcherImpl_8_0.java index d599ca3d4e..fabd2a5ccf 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ServerMethodDispatcherImpl_8_0.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/ServerMethodDispatcherImpl_8_0.java @@ -20,10 +20,19 @@ */ package org.apache.qpid.server.handler; +import org.apache.qpid.AMQException; +import org.apache.qpid.framing.BasicRecoverOkBody; +import org.apache.qpid.framing.ChannelAlertBody; +import org.apache.qpid.framing.TestContentBody; +import org.apache.qpid.framing.TestContentOkBody; +import org.apache.qpid.framing.TestIntegerBody; +import org.apache.qpid.framing.TestIntegerOkBody; +import org.apache.qpid.framing.TestStringBody; +import org.apache.qpid.framing.TestStringOkBody; +import org.apache.qpid.framing.TestTableBody; +import org.apache.qpid.framing.TestTableOkBody; import org.apache.qpid.framing.amqp_8_0.MethodDispatcher_8_0; -import org.apache.qpid.framing.*; import org.apache.qpid.server.state.AMQStateManager; -import org.apache.qpid.AMQException; public class ServerMethodDispatcherImpl_8_0 extends ServerMethodDispatcherImpl diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/TxCommitHandler.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/TxCommitHandler.java index abd2bccc8d..6e8896a023 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/TxCommitHandler.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/TxCommitHandler.java @@ -21,10 +21,11 @@ package org.apache.qpid.server.handler; import org.apache.log4j.Logger; + import org.apache.qpid.AMQException; -import org.apache.qpid.framing.TxCommitBody; -import org.apache.qpid.framing.MethodRegistry; import org.apache.qpid.framing.AMQMethodBody; +import org.apache.qpid.framing.MethodRegistry; +import org.apache.qpid.framing.TxCommitBody; import org.apache.qpid.server.AMQChannel; import org.apache.qpid.server.protocol.AMQProtocolSession; import org.apache.qpid.server.state.AMQStateManager; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/TxRollbackHandler.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/TxRollbackHandler.java index 20ba3af458..010a07be14 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/TxRollbackHandler.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/TxRollbackHandler.java @@ -21,11 +21,9 @@ package org.apache.qpid.server.handler; import org.apache.qpid.AMQException; -import org.apache.qpid.framing.TxRollbackBody; -import org.apache.qpid.framing.TxRollbackOkBody; -import org.apache.qpid.framing.MethodRegistry; import org.apache.qpid.framing.AMQMethodBody; -import org.apache.qpid.protocol.AMQMethodEvent; +import org.apache.qpid.framing.MethodRegistry; +import org.apache.qpid.framing.TxRollbackBody; import org.apache.qpid.server.AMQChannel; import org.apache.qpid.server.protocol.AMQProtocolSession; import org.apache.qpid.server.state.AMQStateManager; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/TxSelectHandler.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/TxSelectHandler.java index 308f5b73cf..44b47704d8 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/TxSelectHandler.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/TxSelectHandler.java @@ -21,14 +21,13 @@ package org.apache.qpid.server.handler; import org.apache.qpid.AMQException; +import org.apache.qpid.framing.MethodRegistry; import org.apache.qpid.framing.TxSelectBody; import org.apache.qpid.framing.TxSelectOkBody; -import org.apache.qpid.framing.MethodRegistry; -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.qpid.server.AMQChannel; public class TxSelectHandler implements StateAwareMethodListener { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/UnexpectedMethodException.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/UnexpectedMethodException.java index 3526fdcae5..cfc52c558c 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/UnexpectedMethodException.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/handler/UnexpectedMethodException.java @@ -21,8 +21,8 @@ package org.apache.qpid.server.handler; -import org.apache.qpid.framing.AMQMethodBody; import org.apache.qpid.AMQException; +import org.apache.qpid.framing.AMQMethodBody; public class UnexpectedMethodException extends AMQException { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/information/management/ServerInformationMBean.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/information/management/ServerInformationMBean.java index 5e6a143d52..4d395f625a 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/information/management/ServerInformationMBean.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/information/management/ServerInformationMBean.java @@ -20,8 +20,6 @@ */ package org.apache.qpid.server.information.management; -import java.io.IOException; - import org.apache.qpid.common.QpidProperties; import org.apache.qpid.management.common.mbeans.ServerInformation; import org.apache.qpid.management.common.mbeans.annotations.MBeanDescription; @@ -29,6 +27,7 @@ import org.apache.qpid.server.management.AMQManagedObject; import org.apache.qpid.server.registry.ApplicationRegistry; import javax.management.JMException; +import java.io.IOException; /** MBean class for the ServerInformationMBean. */ @MBeanDescription("Server Information Interface") diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/Log4jMessageLogger.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/Log4jMessageLogger.java index a0285ebfc4..ec506ab51c 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/Log4jMessageLogger.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/Log4jMessageLogger.java @@ -22,6 +22,7 @@ package org.apache.qpid.server.logging; import org.apache.log4j.Level; import org.apache.log4j.Logger; + import org.apache.qpid.server.configuration.ServerConfiguration; public class Log4jMessageLogger extends AbstractRootMessageLogger diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/actors/AMQPChannelActor.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/actors/AMQPChannelActor.java index 9c7ffcc5f8..50a7e67583 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/actors/AMQPChannelActor.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/actors/AMQPChannelActor.java @@ -23,9 +23,6 @@ package org.apache.qpid.server.logging.actors; import org.apache.qpid.server.AMQChannel; import org.apache.qpid.server.logging.RootMessageLogger; import org.apache.qpid.server.logging.subjects.ChannelLogSubject; -import org.apache.qpid.server.protocol.AMQProtocolSession; - -import java.text.MessageFormat; /** * An AMQPChannelActor represtents a connection through the AMQP port with an diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/actors/AbstractActor.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/actors/AbstractActor.java index e0bf180cc4..e8c6c9c323 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/actors/AbstractActor.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/actors/AbstractActor.java @@ -27,9 +27,9 @@ import org.apache.qpid.server.logging.RootMessageLogger; public abstract class AbstractActor implements LogActor { - public final String _msgPrefix = System.getProperty("qpid.logging.prefix",""); + private final String _msgPrefix = System.getProperty("qpid.logging.prefix",""); - protected RootMessageLogger _rootLogger; + private RootMessageLogger _rootLogger; public AbstractActor(RootMessageLogger rootLogger) { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/actors/CurrentActor.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/actors/CurrentActor.java index 2ebbfeb734..feacf35d41 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/actors/CurrentActor.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/actors/CurrentActor.java @@ -68,6 +68,10 @@ public class CurrentActor private static LogActor _defaultActor; + private CurrentActor() + { + } + /** * Set a new {@link LogActor} to be the Current Actor *

diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/actors/GenericActor.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/actors/GenericActor.java index 9afc76ce78..0e418a95e2 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/actors/GenericActor.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/actors/GenericActor.java @@ -24,7 +24,6 @@ package org.apache.qpid.server.logging.actors; import org.apache.qpid.server.logging.LogActor; import org.apache.qpid.server.logging.LogSubject; import org.apache.qpid.server.logging.RootMessageLogger; -import org.apache.qpid.server.registry.ApplicationRegistry; public class GenericActor extends AbstractActor { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/actors/ManagementActor.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/actors/ManagementActor.java index 286fc78719..9cd3c66629 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/actors/ManagementActor.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/actors/ManagementActor.java @@ -22,14 +22,13 @@ package org.apache.qpid.server.logging.actors; import org.apache.qpid.server.logging.RootMessageLogger; +import javax.management.remote.JMXPrincipal; +import javax.security.auth.Subject; import java.security.AccessController; import java.security.Principal; import java.text.MessageFormat; import java.util.Set; -import javax.management.remote.JMXPrincipal; -import javax.security.auth.Subject; - /** * NOTE: This actor is not thread safe. * @@ -52,7 +51,7 @@ public class ManagementActor extends AbstractActor */ private static final String UNKNOWN_PRINCIPAL = "N/A"; - String _lastThreadName = null; + private String _lastThreadName = null; /** * LOG FORMAT for the ManagementActor, diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/actors/QueueActor.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/actors/QueueActor.java index 3364365b61..4b17e8c0e6 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/actors/QueueActor.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/actors/QueueActor.java @@ -24,8 +24,6 @@ import org.apache.qpid.server.logging.RootMessageLogger; import org.apache.qpid.server.logging.subjects.QueueLogSubject; import org.apache.qpid.server.queue.AMQQueue; -import java.text.MessageFormat; - /** * This Actor is used when while the queue is performing an asynchronous process * of its queue. diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/management/LoggingManagementMBean.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/management/LoggingManagementMBean.java index a823fb7cb1..c699dff175 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/management/LoggingManagementMBean.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/management/LoggingManagementMBean.java @@ -20,35 +20,22 @@ */ package org.apache.qpid.server.logging.management; -import static org.apache.log4j.xml.QpidLog4JConfigurator.LOCK; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Random; - -import org.apache.qpid.management.common.mbeans.LoggingManagement; -import org.apache.qpid.management.common.mbeans.annotations.MBeanDescription; -import org.apache.qpid.server.management.AMQManagedObject; -import org.apache.qpid.util.FileUtils; - import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.apache.log4j.xml.Log4jEntityResolver; import org.apache.log4j.xml.QpidLog4JConfigurator; -import org.apache.log4j.xml.QpidLog4JConfigurator.QpidLog4JSaxErrorHandler; import org.apache.log4j.xml.QpidLog4JConfigurator.IllegalLoggerLevelException; +import org.apache.log4j.xml.QpidLog4JConfigurator.QpidLog4JSaxErrorHandler; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; -import org.xml.sax.SAXParseException; + +import org.apache.qpid.management.common.mbeans.LoggingManagement; +import org.apache.qpid.management.common.mbeans.annotations.MBeanDescription; +import org.apache.qpid.server.management.AMQManagedObject; import javax.management.JMException; import javax.management.openmbean.CompositeData; @@ -69,6 +56,16 @@ import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; + +import static org.apache.log4j.xml.QpidLog4JConfigurator.LOCK; /** MBean class for BrokerLoggingManagerMBean. It implements all the management features exposed for managing logging. */ @@ -85,8 +82,8 @@ public class LoggingManagementMBean extends AMQManagedObject implements LoggingM Level.WARN.toString(), Level.ERROR.toString(), Level.FATAL.toString(),Level.OFF.toString(), INHERITED}; - static TabularType _loggerLevelTabularType; - static CompositeType _loggerLevelCompositeType; + private static TabularType _loggerLevelTabularType; + private static CompositeType _loggerLevelCompositeType; static { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/messages/Broker_logmessages.properties b/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/messages/Broker_logmessages.properties index 5d1e85fe41..1aa7815c39 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/messages/Broker_logmessages.properties +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/messages/Broker_logmessages.properties @@ -26,7 +26,7 @@ STARTUP = BRK-1001 : Startup : Version: {0} Build: {1} LISTENING = BRK-1002 : Starting : Listening on {0} port {1,number,#} # 0 - Transport # 1 - Port -SHUTTING_DOWN = BRK-1003 : Shuting down : {0} port {1,number,#} +SHUTTING_DOWN = BRK-1003 : Shutting down : {0} port {1,number,#} READY = BRK-1004 : Qpid Broker Ready STOPPED = BRK-1005 : Stopped # 0 - path @@ -35,4 +35,14 @@ CONFIG = BRK-1006 : Using configuration : {0} LOG_CONFIG = BRK-1007 : Using logging configuration : {0} STATS_DATA = BRK-1008 : {0,choice,0#delivered|1#received} : {1,number,#.###} kB/s peak : {2,number,#} bytes total -STATS_MSGS = BRK-1009 : {0,choice,0#delivered|1#received} : {1,number,#.###} msg/s peak : {2,number,#} msgs total \ No newline at end of file +STATS_MSGS = BRK-1009 : {0,choice,0#delivered|1#received} : {1,number,#.###} msg/s peak : {2,number,#} msgs total + +# 0 - java vendor +# 1 - java runtime version +# 2 - os name +# 3 - os type +# 4 - os architecture +PLATFORM = BRK-1010 : Platform : JVM : {0} version: {1} OS : {2} version: {3} arch: {4} + +# 0 Maximum Memory +MAX_MEMORY = BRK-1011 : Maximum Memory : {0,number} bytes \ No newline at end of file diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/messages/Connection_logmessages.properties b/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/messages/Connection_logmessages.properties index 81ae6f3bd0..8559862a45 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/messages/Connection_logmessages.properties +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/messages/Connection_logmessages.properties @@ -20,5 +20,6 @@ # 0 - Client id # 1 - Protocol Version -OPEN = CON-1001 : Open[ : Client ID : {0}][ : Protocol Version : {1}] +# 2 - Client Version +OPEN = CON-1001 : Open[ : Client ID : {0}][ : Protocol Version : {1}][ : Client Version : {2}] CLOSE = CON-1002 : Close \ No newline at end of file diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/messages/TransactionLog_logmessages.properties b/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/messages/TransactionLog_logmessages.properties index fadc2e2098..9ef58df940 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/messages/TransactionLog_logmessages.properties +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/messages/TransactionLog_logmessages.properties @@ -31,3 +31,9 @@ RECOVERY_START = TXN-1004 : Recovery Start[ : {0}] RECOVERED = TXN-1005 : Recovered {0,number} messages for queue {1} # 0 - queue name RECOVERY_COMPLETE = TXN-1006 : Recovery Complete[ : {0}] +# 0 - xid +# 1 - queue name +XA_INCOMPLETE_QUEUE = TXN-1007 : XA transaction recover for xid {0} incomplete as it references a queue {1} which was not durably retained +# 0 - xid format +# 1 - message id +XA_INCOMPLETE_MESSAGE = TXN-1008 : XA transaction recover for xid {0} incomplete as it references a message {1} which was not durably retained diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/AbstractLogSubject.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/AbstractLogSubject.java index 779db01601..baccf240ff 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/AbstractLogSubject.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/AbstractLogSubject.java @@ -33,10 +33,7 @@ import java.text.MessageFormat; */ public abstract class AbstractLogSubject implements LogSubject { - /** - * The logString that will be returned via toLogString - */ - protected String _logString; + private String _logString; /** * Set the toString logging of this LogSubject. Based on a format provided @@ -60,4 +57,16 @@ public abstract class AbstractLogSubject implements LogSubject return _logString; } + /** + * The logString that will be returned via toLogString + */ + public String getLogString() + { + return _logString; + } + + public void setLogString(String logString) + { + _logString = logString; + } } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/BindingLogSubject.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/BindingLogSubject.java index 088b59ae68..8f0b9182a9 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/BindingLogSubject.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/BindingLogSubject.java @@ -22,6 +22,7 @@ package org.apache.qpid.server.logging.subjects; import org.apache.qpid.server.exchange.Exchange; import org.apache.qpid.server.queue.AMQQueue; + import static org.apache.qpid.server.logging.subjects.LogSubjectFormat.BINDING_FORMAT; public class BindingLogSubject extends AbstractLogSubject diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/ChannelLogSubject.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/ChannelLogSubject.java index 885b039e18..859d7e2a27 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/ChannelLogSubject.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/ChannelLogSubject.java @@ -36,8 +36,7 @@ public class ChannelLogSubject extends AbstractLogSubject /** * LOG FORMAT used by the AMQPConnectorActor follows - * ChannelLogSubject.CHANNEL_FORMAT : - * con:{0}({1}@{2}/{3})/ch:{4} + * ChannelLogSubject.CHANNEL_FORMAT : con:{0}({1}@{2}/{3})/ch:{4}. * * Uses a MessageFormat call to insert the required values according to * these indices: @@ -60,8 +59,7 @@ public class ChannelLogSubject extends AbstractLogSubject { /** * LOG FORMAT used by the AMQPConnectorActor follows - * ChannelLogSubject.CHANNEL_FORMAT : - * con:{0}({1}@{2}/{3})/ch:{4} + * ChannelLogSubject.CHANNEL_FORMAT : con:{0}({1}@{2}/{3})/ch:{4}. * * Uses a MessageFormat call to insert the required values according to * these indices: diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/ConnectionLogSubject.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/ConnectionLogSubject.java index c1c836f9b4..3b08a172b6 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/ConnectionLogSubject.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/ConnectionLogSubject.java @@ -22,11 +22,11 @@ package org.apache.qpid.server.logging.subjects; import org.apache.qpid.server.protocol.AMQProtocolSession; -import java.text.MessageFormat; - +import static org.apache.qpid.server.logging.subjects.LogSubjectFormat.CONNECTION_FORMAT; import static org.apache.qpid.server.logging.subjects.LogSubjectFormat.SOCKET_FORMAT; import static org.apache.qpid.server.logging.subjects.LogSubjectFormat.USER_FORMAT; -import static org.apache.qpid.server.logging.subjects.LogSubjectFormat.CONNECTION_FORMAT; + +import java.text.MessageFormat; /** The Connection LogSubject */ public class ConnectionLogSubject extends AbstractLogSubject @@ -70,31 +70,31 @@ public class ConnectionLogSubject extends AbstractLogSubject * * 0 - Connection ID 1 - User ID 2 - IP 3 - Virtualhost */ - _logString = "[" + MessageFormat.format(CONNECTION_FORMAT, - _session.getSessionID(), - _session.getAuthorizedPrincipal().getName(), + setLogString("[" + MessageFormat.format(CONNECTION_FORMAT, + _session.getSessionID(), + _session.getAuthorizedPrincipal().getName(), _session.getRemoteAddress(), - _session.getVirtualHost().getName()) - + "] "; + _session.getVirtualHost().getName()) + + "] "); _upToDate = true; } else { - _logString = "[" + MessageFormat.format(USER_FORMAT, - _session.getSessionID(), - _session.getAuthorizedPrincipal().getName(), + setLogString("[" + MessageFormat.format(USER_FORMAT, + _session.getSessionID(), + _session.getAuthorizedPrincipal().getName(), _session.getRemoteAddress()) - + "] "; + + "] "); } } else { - _logString = "[" + MessageFormat.format(SOCKET_FORMAT, + setLogString("[" + MessageFormat.format(SOCKET_FORMAT, _session.getSessionID(), - _session.getRemoteAddress()) - + "] "; + _session.getRemoteAddress()) + + "] "); } } } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/ExchangeLogSubject.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/ExchangeLogSubject.java index 6ab44a92b9..99a54cc6d0 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/ExchangeLogSubject.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/ExchangeLogSubject.java @@ -22,6 +22,7 @@ package org.apache.qpid.server.logging.subjects; import org.apache.qpid.server.exchange.Exchange; import org.apache.qpid.server.virtualhost.VirtualHost; + import static org.apache.qpid.server.logging.subjects.LogSubjectFormat.EXCHANGE_FORMAT; public class ExchangeLogSubject extends AbstractLogSubject diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/LogSubjectFormat.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/LogSubjectFormat.java index ff2bb90140..28c4f0d52a 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/LogSubjectFormat.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/LogSubjectFormat.java @@ -32,7 +32,10 @@ package org.apache.qpid.server.logging.subjects; public class LogSubjectFormat { - + private LogSubjectFormat() + { + } + /** * LOG FORMAT for the Subscription Log Subject * 0 - Subscription ID diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/MessageStoreLogSubject.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/MessageStoreLogSubject.java index 3fce13bcb5..969288be00 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/MessageStoreLogSubject.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/MessageStoreLogSubject.java @@ -20,8 +20,9 @@ */ package org.apache.qpid.server.logging.subjects; -import org.apache.qpid.server.virtualhost.VirtualHost; import org.apache.qpid.server.store.MessageStore; +import org.apache.qpid.server.virtualhost.VirtualHost; + import static org.apache.qpid.server.logging.subjects.LogSubjectFormat.STORE_FORMAT; public class MessageStoreLogSubject extends AbstractLogSubject diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/QueueLogSubject.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/QueueLogSubject.java index bfe12f1a60..53a9ab75d9 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/QueueLogSubject.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/QueueLogSubject.java @@ -21,6 +21,7 @@ package org.apache.qpid.server.logging.subjects; import org.apache.qpid.server.queue.AMQQueue; + import static org.apache.qpid.server.logging.subjects.LogSubjectFormat.QUEUE_FORMAT; public class QueueLogSubject extends AbstractLogSubject diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/SubscriptionLogSubject.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/SubscriptionLogSubject.java index 8b57647046..9a23b733dc 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/SubscriptionLogSubject.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/SubscriptionLogSubject.java @@ -22,10 +22,10 @@ package org.apache.qpid.server.logging.subjects; import org.apache.qpid.server.subscription.Subscription; -import java.text.MessageFormat; - import static org.apache.qpid.server.logging.subjects.LogSubjectFormat.SUBSCRIPTION_FORMAT; +import java.text.MessageFormat; + public class SubscriptionLogSubject extends AbstractLogSubject { @@ -42,14 +42,14 @@ public class SubscriptionLogSubject extends AbstractLogSubject String queueString = new QueueLogSubject(subscription.getQueue()).toLogString(); - _logString = "[" + MessageFormat.format(SUBSCRIPTION_FORMAT, + setLogString("[" + MessageFormat.format(SUBSCRIPTION_FORMAT, subscription.getSubscriptionID()) + "(" // queueString is [vh(/{0})/qu({1}) ] so need to trim // ^ ^^ + queueString.substring(1,queueString.length() - 3) + ")" - + "] "; + + "] "); } } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/management/AMQManagedObject.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/management/AMQManagedObject.java index 6c9d6e39de..5c57c01f6e 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/management/AMQManagedObject.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/management/AMQManagedObject.java @@ -20,13 +20,11 @@ */ package org.apache.qpid.server.management; -import org.apache.qpid.server.logging.actors.ManagementActor; -import org.apache.qpid.server.logging.actors.CurrentActor; import org.apache.qpid.server.logging.LogActor; +import org.apache.qpid.server.logging.actors.CurrentActor; +import org.apache.qpid.server.logging.actors.ManagementActor; import javax.management.ListenerNotFoundException; -import javax.management.MBeanInfo; -import javax.management.MBeanNotificationInfo; import javax.management.NotCompliantMBeanException; import javax.management.NotificationBroadcaster; import javax.management.NotificationBroadcasterSupport; @@ -42,17 +40,11 @@ import javax.management.NotificationListener; public abstract class AMQManagedObject extends DefaultManagedObject implements NotificationBroadcaster { - /** - * broadcaster support class - */ - protected NotificationBroadcasterSupport _broadcaster = new NotificationBroadcasterSupport(); + private NotificationBroadcasterSupport _broadcaster = new NotificationBroadcasterSupport(); - /** - * sequence number for notifications - */ - protected long _notificationSequenceNumber = 0; + private long _notificationSequenceNumber = 0; - protected LogActor _logActor; + private LogActor _logActor; protected AMQManagedObject(Class managementInterface, String typeName) throws NotCompliantMBeanException @@ -79,4 +71,35 @@ public abstract class AMQManagedObject extends DefaultManagedObject } + /** + * broadcaster support class + */ + protected NotificationBroadcasterSupport getBroadcaster() + { + return _broadcaster; + } + + /** + * sequence number for notifications + */ + protected long getNotificationSequenceNumber() + { + return _notificationSequenceNumber; + } + + protected void setNotificationSequenceNumber(long notificationSequenceNumber) + { + _notificationSequenceNumber = notificationSequenceNumber; + } + + protected long incrementAndGetSequenceNumber() + { + return ++_notificationSequenceNumber; + } + + protected LogActor getLogActor() + { + return _logActor; + } + } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/management/AbstractAMQManagedConnectionObject.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/management/AbstractAMQManagedConnectionObject.java index 68350a1632..e7c07b6dd4 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/management/AbstractAMQManagedConnectionObject.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/management/AbstractAMQManagedConnectionObject.java @@ -1,21 +1,21 @@ package org.apache.qpid.server.management; -import javax.management.Notification; +import org.apache.qpid.management.common.mbeans.ManagedConnection; import javax.management.JMException; import javax.management.MBeanNotificationInfo; import javax.management.NotCompliantMBeanException; +import javax.management.Notification; import javax.management.ObjectName; import javax.management.monitor.MonitorNotification; import javax.management.openmbean.CompositeType; import javax.management.openmbean.OpenType; import javax.management.openmbean.SimpleType; import javax.management.openmbean.TabularType; -import org.apache.qpid.management.common.mbeans.ManagedConnection; public abstract class AbstractAMQManagedConnectionObject extends AMQManagedObject implements ManagedConnection { - protected final String _name; + private final String _name; protected static final OpenType[] _channelAttributeTypes = { SimpleType.INTEGER, SimpleType.BOOLEAN, SimpleType.STRING, SimpleType.INTEGER, SimpleType.BOOLEAN }; protected static final CompositeType _channelType; @@ -45,7 +45,6 @@ public abstract class AbstractAMQManagedConnectionObject extends AMQManagedObjec _name = "anonymous".equals(remoteAddress) ? (remoteAddress + hashCode()) : remoteAddress; } - @Override public String getObjectInstanceName() { return ObjectName.quote(_name); @@ -53,9 +52,9 @@ public abstract class AbstractAMQManagedConnectionObject extends AMQManagedObjec public void notifyClients(String notificationMsg) { - final Notification n = new Notification(MonitorNotification.THRESHOLD_VALUE_EXCEEDED, this, ++_notificationSequenceNumber, + final Notification n = new Notification(MonitorNotification.THRESHOLD_VALUE_EXCEEDED, this, incrementAndGetSequenceNumber(), System.currentTimeMillis(), notificationMsg); - _broadcaster.sendNotification(n); + getBroadcaster().sendNotification(n); } @Override diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/management/DefaultManagedObject.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/management/DefaultManagedObject.java index 0c3a5fc571..10d7503800 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/management/DefaultManagedObject.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/management/DefaultManagedObject.java @@ -20,6 +20,10 @@ */ package org.apache.qpid.server.management; +import org.apache.log4j.Logger; + +import org.apache.qpid.server.registry.ApplicationRegistry; + import javax.management.JMException; import javax.management.MBeanInfo; import javax.management.MBeanNotificationInfo; @@ -28,9 +32,6 @@ import javax.management.NotCompliantMBeanException; import javax.management.ObjectName; import javax.management.StandardMBean; -import org.apache.log4j.Logger; -import org.apache.qpid.server.registry.ApplicationRegistry; - /** * Provides implementation of the boilerplate ManagedObject interface. Most managed objects should find it useful * to extend this class rather than implementing ManagedObject from scratch. @@ -153,7 +154,9 @@ public abstract class DefaultManagedObject extends StandardMBean implements Mana return parentType + "." + obj.getType(); } else + { return obj.getType(); + } } protected String getHierarchicalName(ManagedObject obj) @@ -167,7 +170,9 @@ public abstract class DefaultManagedObject extends StandardMBean implements Mana return parentName; } else + { return ""; + } } private MBeanInfo buildMBeanInfo() throws NotCompliantMBeanException diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/management/JMXManagedObjectRegistry.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/management/JMXManagedObjectRegistry.java index 8583e8d57b..04a5b27991 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/management/JMXManagedObjectRegistry.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/management/JMXManagedObjectRegistry.java @@ -20,6 +20,35 @@ */ package org.apache.qpid.server.management; +import org.apache.commons.configuration.ConfigurationException; +import org.apache.log4j.Logger; + +import org.apache.qpid.AMQException; +import org.apache.qpid.server.logging.actors.CurrentActor; +import org.apache.qpid.server.logging.messages.ManagementConsoleMessages; +import org.apache.qpid.server.registry.ApplicationRegistry; +import org.apache.qpid.server.registry.IApplicationRegistry; +import org.apache.qpid.server.security.auth.rmi.RMIPasswordAuthenticator; +import org.apache.qpid.server.security.auth.sasl.UsernamePrincipal; + +import javax.management.JMException; +import javax.management.MBeanServer; +import javax.management.MBeanServerFactory; +import javax.management.Notification; +import javax.management.NotificationFilterSupport; +import javax.management.NotificationListener; +import javax.management.ObjectName; +import javax.management.remote.JMXConnectionNotification; +import javax.management.remote.JMXConnectorServer; +import javax.management.remote.JMXServiceURL; +import javax.management.remote.MBeanServerForwarder; +import javax.management.remote.rmi.RMIConnection; +import javax.management.remote.rmi.RMIConnectorServer; +import javax.management.remote.rmi.RMIJRMPServerImpl; +import javax.management.remote.rmi.RMIServerImpl; +import javax.rmi.ssl.SslRMIClientSocketFactory; +import javax.rmi.ssl.SslRMIServerSocketFactory; +import javax.security.auth.Subject; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; @@ -41,35 +70,6 @@ import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -import javax.management.JMException; -import javax.management.MBeanServer; -import javax.management.MBeanServerFactory; -import javax.management.Notification; -import javax.management.NotificationFilterSupport; -import javax.management.NotificationListener; -import javax.management.ObjectName; -import javax.management.remote.JMXConnectionNotification; -import javax.management.remote.JMXConnectorServer; -import javax.management.remote.JMXServiceURL; -import javax.management.remote.MBeanServerForwarder; -import javax.management.remote.rmi.RMIConnection; -import javax.management.remote.rmi.RMIConnectorServer; -import javax.management.remote.rmi.RMIJRMPServerImpl; -import javax.management.remote.rmi.RMIServerImpl; -import javax.rmi.ssl.SslRMIClientSocketFactory; -import javax.rmi.ssl.SslRMIServerSocketFactory; -import javax.security.auth.Subject; - -import org.apache.commons.configuration.ConfigurationException; -import org.apache.log4j.Logger; -import org.apache.qpid.AMQException; -import org.apache.qpid.server.logging.actors.CurrentActor; -import org.apache.qpid.server.logging.messages.ManagementConsoleMessages; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.registry.IApplicationRegistry; -import org.apache.qpid.server.security.auth.rmi.RMIPasswordAuthenticator; -import org.apache.qpid.server.security.auth.sasl.UsernamePrincipal; - /** * This class starts up an MBeanserver. If out of the box agent has been enabled then there are no * security features implemented like user authentication and authorisation. @@ -157,9 +157,7 @@ public class JMXManagedObjectRegistry implements ManagedObjectRegistry if (!ksf.exists()) { - throw new FileNotFoundException("Cannot find JMX management SSL keystore file " + ksf + "\n" - + "Check broker configuration, or see create-example-ssl-stores script" - + "in the bin/ directory if you need to generate an example store."); + throw new FileNotFoundException("Cannot find JMX management SSL keystore file: " + ksf); } if (!ksf.canRead()) { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/management/MBeanIntrospector.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/management/MBeanIntrospector.java index 17a6851abc..89b74f939d 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/management/MBeanIntrospector.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/management/MBeanIntrospector.java @@ -20,23 +20,22 @@ */ package org.apache.qpid.server.management; -import java.lang.annotation.Annotation; -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; +import org.apache.qpid.management.common.mbeans.annotations.MBeanAttribute; +import org.apache.qpid.management.common.mbeans.annotations.MBeanConstructor; +import org.apache.qpid.management.common.mbeans.annotations.MBeanDescription; +import org.apache.qpid.management.common.mbeans.annotations.MBeanOperation; +import org.apache.qpid.management.common.mbeans.annotations.MBeanOperationParameter; import javax.management.MBeanAttributeInfo; import javax.management.MBeanConstructorInfo; import javax.management.MBeanOperationInfo; import javax.management.MBeanParameterInfo; import javax.management.NotCompliantMBeanException; - -import org.apache.qpid.management.common.mbeans.annotations.MBeanAttribute; -import org.apache.qpid.management.common.mbeans.annotations.MBeanConstructor; -import org.apache.qpid.management.common.mbeans.annotations.MBeanDescription; -import org.apache.qpid.management.common.mbeans.annotations.MBeanOperation; -import org.apache.qpid.management.common.mbeans.annotations.MBeanOperationParameter; +import java.lang.annotation.Annotation; +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; /** * This class is a utility class to introspect the MBean class and the management @@ -51,6 +50,10 @@ class MBeanIntrospector { private static final String _defaultConstructorDescription = "MBean constructor"; private static final String _defaultMbeanDescription = "Management interface of the MBean"; + private MBeanIntrospector() + { + } + /** * Introspects the management interface class for MBean attributes. * @param interfaceClass @@ -328,7 +331,9 @@ class MBeanIntrospector { paramInfo = new MBeanParameterInfo("p " + (i + 1), type, "parameter " + (i + 1)); } if (paramInfo != null) + { paramsInfo[i] = paramInfo; + } } return paramsInfo; @@ -346,9 +351,10 @@ class MBeanIntrospector { for (Constructor cons : implClass.getConstructors()) { MBeanConstructorInfo constructorInfo = getMBeanConstructorInfo(cons); - //MBeanConstructorInfo constructorInfo = new MBeanConstructorInfo("desc", cons); if (constructorInfo != null) + { constructors.add(constructorInfo); + } } return constructors.toArray(new MBeanConstructorInfo[0]); @@ -372,9 +378,6 @@ class MBeanIntrospector { } } - //MBeanParameterInfo[] paramsInfo = getParametersInfo(cons.getParameterAnnotations(), - // cons.getParameterTypes()); - return new MBeanConstructorInfo(cons.getName(), desc, null); } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/management/MBeanInvocationHandlerImpl.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/management/MBeanInvocationHandlerImpl.java index 40a221e0ba..651372db16 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/management/MBeanInvocationHandlerImpl.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/management/MBeanInvocationHandlerImpl.java @@ -20,14 +20,14 @@ */ package org.apache.qpid.server.management; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.security.AccessControlContext; -import java.security.AccessController; -import java.util.Map; -import java.util.Set; +import org.apache.log4j.Logger; + +import org.apache.qpid.server.logging.actors.ManagementActor; +import org.apache.qpid.server.logging.messages.ManagementConsoleMessages; +import org.apache.qpid.server.registry.ApplicationRegistry; +import org.apache.qpid.server.registry.IApplicationRegistry; +import org.apache.qpid.server.security.SecurityManager; +import org.apache.qpid.server.security.access.Operation; import javax.management.Attribute; import javax.management.JMException; @@ -41,14 +41,14 @@ import javax.management.remote.JMXConnectionNotification; import javax.management.remote.JMXPrincipal; import javax.management.remote.MBeanServerForwarder; import javax.security.auth.Subject; - -import org.apache.log4j.Logger; -import org.apache.qpid.server.logging.actors.ManagementActor; -import org.apache.qpid.server.logging.messages.ManagementConsoleMessages; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.registry.IApplicationRegistry; -import org.apache.qpid.server.security.SecurityManager; -import org.apache.qpid.server.security.access.Operation; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.security.AccessControlContext; +import java.security.AccessController; +import java.util.Map; +import java.util.Set; /** * This class can be used by the JMXConnectorServer as an InvocationHandler for the mbean operations. It delegates @@ -87,8 +87,8 @@ public class MBeanInvocationHandlerImpl implements InvocationHandler, Notificati return true; } - // Allow querying available object names - if (methodName.equals("queryNames")) + // Allow querying available object names and mbeans + if (methodName.equals("queryNames") || methodName.equals("queryMBeans")) { return true; } @@ -108,7 +108,7 @@ public class MBeanInvocationHandlerImpl implements InvocationHandler, Notificati public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - final String methodName = getMethodName(method, args); + String methodName = method.getName(); if (methodName.equals("getMBeanServer")) { @@ -173,6 +173,7 @@ public class MBeanInvocationHandlerImpl implements InvocationHandler, Notificati security = _appRegistry.getVirtualHostRegistry().getVirtualHost(vhost).getSecurityManager(); } + methodName = getMethodName(method, args); if (isAccessMethod(methodName) || impact == MBeanOperationInfo.INFO) { // Check for read-only method invocation permission @@ -339,7 +340,7 @@ public class MBeanInvocationHandlerImpl implements InvocationHandler, Notificati // Normally JMXManagedObjectRegistry provides a Map as handback data containing a map // between connection id and username. String user = null; - if (handback != null && handback instanceof Map) + if (handback instanceof Map) { final Map connectionIdUsernameMap = (Map) handback; user = connectionIdUsernameMap.get(connectionId); diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/management/ManagedObject.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/management/ManagedObject.java index de14785fb0..483b325455 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/management/ManagedObject.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/management/ManagedObject.java @@ -20,11 +20,11 @@ */ package org.apache.qpid.server.management; +import org.apache.qpid.AMQException; + +import javax.management.JMException; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; -import javax.management.JMException; - -import org.apache.qpid.AMQException; /** * This should be implemented by all Managable objects. diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/management/ManagedObjectRegistry.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/management/ManagedObjectRegistry.java index fda80ad0dd..b3323c569c 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/management/ManagedObjectRegistry.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/management/ManagedObjectRegistry.java @@ -20,12 +20,11 @@ */ package org.apache.qpid.server.management; -import javax.management.JMException; - import org.apache.commons.configuration.ConfigurationException; + import org.apache.qpid.common.Closeable; -import java.rmi.RemoteException; +import javax.management.JMException; import java.io.IOException; /** diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/management/NoopManagedObjectRegistry.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/management/NoopManagedObjectRegistry.java index a048e75b2e..e77350c3e4 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/management/NoopManagedObjectRegistry.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/management/NoopManagedObjectRegistry.java @@ -20,11 +20,9 @@ */ package org.apache.qpid.server.management; -import javax.management.JMException; - import org.apache.log4j.Logger; -import java.rmi.RemoteException; +import javax.management.JMException; /** * This managed object registry does not actually register MBeans. This can be used in tests when management is diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/message/AMQMessage.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/message/AMQMessage.java index e36e467fea..29b4eac89f 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/message/AMQMessage.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/message/AMQMessage.java @@ -21,15 +21,14 @@ package org.apache.qpid.server.message; import org.apache.log4j.Logger; + import org.apache.qpid.AMQException; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.framing.ContentHeaderBody; import org.apache.qpid.framing.abstraction.MessagePublishInfo; import org.apache.qpid.server.AMQChannel; -import org.apache.qpid.server.store.StoredMessage; -import org.apache.qpid.server.configuration.SessionConfig; import org.apache.qpid.server.queue.AMQQueue; - +import org.apache.qpid.server.store.StoredMessage; import java.lang.ref.WeakReference; import java.nio.ByteBuffer; @@ -59,7 +58,7 @@ public class AMQMessage extends AbstractServerMessageImpl private final long _size; - private Object _sessionIdentifier; + private Object _connectionIdentifier; private static final byte IMMEDIATE_AND_DELIVERED = (byte) (IMMEDIATE | DELIVERED_TO_CONSUMER); private WeakReference _channelRef; @@ -223,19 +222,15 @@ public class AMQMessage extends AbstractServerMessageImpl } - public Object getPublisherIdentifier() + public Object getConnectionIdentifier() { - //todo store sessionIdentifier/client id with message in store - //Currently the _sessionIdentifier will be null if the message has been - // restored from a message Store - - return _sessionIdentifier; + return _connectionIdentifier; } - public void setClientIdentifier(final Object sessionIdentifier) + public void setConnectionIdentifier(final Object connectionIdentifier) { - _sessionIdentifier = sessionIdentifier; + _connectionIdentifier = connectionIdentifier; } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/message/AMQMessageReference.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/message/AMQMessageReference.java index 940caaefe4..62cfa8431c 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/message/AMQMessageReference.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/message/AMQMessageReference.java @@ -20,9 +20,6 @@ */ package org.apache.qpid.server.message; -import org.apache.qpid.server.message.AMQMessage; -import org.apache.qpid.server.queue.MessageCleanupException; - public class AMQMessageReference extends MessageReference { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/message/AbstractServerMessageImpl.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/message/AbstractServerMessageImpl.java index b1d43f0b50..587b76a12e 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/message/AbstractServerMessageImpl.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/message/AbstractServerMessageImpl.java @@ -20,12 +20,11 @@ */ package org.apache.qpid.server.message; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; - import org.apache.qpid.server.store.StorableMessageMetaData; import org.apache.qpid.server.store.StoredMessage; +import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; + public abstract class AbstractServerMessageImpl implements ServerMessage { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/message/ContentHeaderBodyAdapter.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/message/ContentHeaderBodyAdapter.java index 84a1642578..e87b67d242 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/message/ContentHeaderBodyAdapter.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/message/ContentHeaderBodyAdapter.java @@ -20,8 +20,8 @@ */ package org.apache.qpid.server.message; -import org.apache.qpid.framing.ContentHeaderBody; import org.apache.qpid.framing.BasicContentHeaderProperties; +import org.apache.qpid.framing.ContentHeaderBody; import org.apache.qpid.framing.FieldTable; import java.util.Set; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/message/InboundMessage.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/message/InboundMessage.java index 79d5574a91..c6dbb49061 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/message/InboundMessage.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/message/InboundMessage.java @@ -21,8 +21,8 @@ package org.apache.qpid.server.message; -import org.apache.qpid.server.queue.Filterable; import org.apache.qpid.framing.AMQShortString; +import org.apache.qpid.server.queue.Filterable; public interface InboundMessage extends Filterable { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/message/MessageMetaData.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/message/MessageMetaData.java index 9bfa0bb2fb..583f0c09a7 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/message/MessageMetaData.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/message/MessageMetaData.java @@ -20,19 +20,21 @@ */ package org.apache.qpid.server.message; -import org.apache.qpid.framing.ContentHeaderBody; +import org.apache.qpid.AMQException; +import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.framing.BasicContentHeaderProperties; +import org.apache.qpid.framing.ContentHeaderBody; import org.apache.qpid.framing.EncodingUtils; -import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.framing.FieldTable; import org.apache.qpid.framing.abstraction.MessagePublishInfo; -import org.apache.qpid.server.store.StorableMessageMetaData; import org.apache.qpid.server.store.MessageMetaDataType; -import org.apache.qpid.AMQException; +import org.apache.qpid.server.store.StorableMessageMetaData; import org.apache.qpid.server.util.ByteBufferOutputStream; import org.apache.qpid.util.ByteBufferInputStream; -import java.io.*; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; import java.nio.ByteBuffer; import java.util.Set; @@ -159,7 +161,7 @@ public class MessageMetaData implements StorableMessageMetaData public int getContentSize() { - return (int) _contentHeaderBody.bodySize; + return (int) _contentHeaderBody.getBodySize(); } public boolean isPersistent() diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/message/MessageMetaData_0_10.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/message/MessageMetaData_0_10.java index 17ebb6ee07..88b0f60346 100755 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/message/MessageMetaData_0_10.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/message/MessageMetaData_0_10.java @@ -20,20 +20,19 @@ */ package org.apache.qpid.server.message; -import org.apache.qpid.server.store.StorableMessageMetaData; +import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.server.store.MessageMetaDataType; -import org.apache.qpid.transport.MessageTransfer; +import org.apache.qpid.server.store.StorableMessageMetaData; import org.apache.qpid.transport.DeliveryProperties; -import org.apache.qpid.transport.MessageProperties; import org.apache.qpid.transport.Header; import org.apache.qpid.transport.MessageDeliveryMode; +import org.apache.qpid.transport.MessageProperties; +import org.apache.qpid.transport.MessageTransfer; import org.apache.qpid.transport.Struct; -import org.apache.qpid.transport.codec.BBEncoder; import org.apache.qpid.transport.codec.BBDecoder; -import org.apache.qpid.framing.AMQShortString; +import org.apache.qpid.transport.codec.BBEncoder; import java.nio.ByteBuffer; -import java.lang.ref.SoftReference; import java.util.ArrayList; import java.util.List; @@ -51,6 +50,7 @@ public class MessageMetaData_0_10 implements StorableMessageMetaData, InboundMes public static final MessageMetaDataType.Factory FACTORY = new MetaDataFactory(); private volatile ByteBuffer _encoded; + private Object _connectionReference; public MessageMetaData_0_10(MessageTransfer xfr) @@ -220,6 +220,16 @@ public class MessageMetaData_0_10 implements StorableMessageMetaData, InboundMes return _header; } + public void setConnectionReference(Object connectionReference) + { + _connectionReference = connectionReference; + } + + public Object getConnectionReference() + { + return _connectionReference; + } + private static class MetaDataFactory implements MessageMetaDataType.Factory { public MessageMetaData_0_10 createMetaData(ByteBuffer buf) diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/message/MessageTransferHeader.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/message/MessageTransferHeader.java index 2f30f260c9..126e7c28cb 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/message/MessageTransferHeader.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/message/MessageTransferHeader.java @@ -21,11 +21,11 @@ package org.apache.qpid.server.message; import org.apache.qpid.transport.DeliveryProperties; -import org.apache.qpid.transport.MessageProperties; import org.apache.qpid.transport.MessageDeliveryPriority; +import org.apache.qpid.transport.MessageProperties; -import java.util.Set; import java.util.Map; +import java.util.Set; import java.util.UUID; class MessageTransferHeader implements AMQMessageHeader diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/message/MessageTransferMessage.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/message/MessageTransferMessage.java index c4d2a190e6..e4de65d192 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/message/MessageTransferMessage.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/message/MessageTransferMessage.java @@ -20,11 +20,9 @@ */ package org.apache.qpid.server.message; -import org.apache.qpid.transport.*; -import org.apache.qpid.server.configuration.SessionConfig; -import org.apache.qpid.server.store.StoredMessage; -import org.apache.qpid.server.transport.ServerSession; import org.apache.qpid.framing.AMQShortString; +import org.apache.qpid.server.store.StoredMessage; +import org.apache.qpid.transport.Header; import java.nio.ByteBuffer; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/message/ServerMessage.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/message/ServerMessage.java index d354d3b145..e1ad2fd0ca 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/message/ServerMessage.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/message/ServerMessage.java @@ -20,11 +20,11 @@ */ package org.apache.qpid.server.message; -import java.nio.ByteBuffer; - import org.apache.qpid.server.store.StorableMessageMetaData; import org.apache.qpid.server.store.StoredMessage; +import java.nio.ByteBuffer; + public interface ServerMessage extends EnqueableMessage, MessageContentSource { String getRoutingKey(); diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/output/HeaderPropertiesConverter.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/output/HeaderPropertiesConverter.java index fa06a99204..72d14456ed 100755 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/output/HeaderPropertiesConverter.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/output/HeaderPropertiesConverter.java @@ -20,21 +20,28 @@ */ package org.apache.qpid.server.output; +import org.apache.qpid.AMQPInvalidClassException; import org.apache.qpid.exchange.ExchangeDefaults; -import org.apache.qpid.server.exchange.Exchange; -import org.apache.qpid.server.message.MessageTransferMessage; -import org.apache.qpid.framing.BasicContentHeaderProperties; import org.apache.qpid.framing.AMQShortString; +import org.apache.qpid.framing.BasicContentHeaderProperties; import org.apache.qpid.framing.FieldTable; +import org.apache.qpid.server.exchange.Exchange; +import org.apache.qpid.server.message.MessageTransferMessage; import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.transport.*; -import org.apache.qpid.AMQPInvalidClassException; +import org.apache.qpid.transport.DeliveryProperties; +import org.apache.qpid.transport.Header; +import org.apache.qpid.transport.MessageDeliveryMode; +import org.apache.qpid.transport.MessageProperties; +import org.apache.qpid.transport.ReplyTo; import java.util.HashMap; import java.util.Map; public class HeaderPropertiesConverter { + private HeaderPropertiesConverter() + { + } public static BasicContentHeaderProperties convert(MessageTransferMessage messageTransferMessage, VirtualHost vhost) { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/output/ProtocolOutputConverter.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/output/ProtocolOutputConverter.java index 5300bad613..04d81bf2f5 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/output/ProtocolOutputConverter.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/output/ProtocolOutputConverter.java @@ -26,14 +26,14 @@ */ package org.apache.qpid.server.output; -import org.apache.qpid.server.queue.QueueEntry; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.message.MessageContentSource; -import org.apache.qpid.framing.AMQShortString; +import org.apache.qpid.AMQException; import org.apache.qpid.framing.AMQDataBlock; +import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.framing.ContentHeaderBody; import org.apache.qpid.framing.abstraction.MessagePublishInfo; -import org.apache.qpid.AMQException; +import org.apache.qpid.server.message.MessageContentSource; +import org.apache.qpid.server.protocol.AMQProtocolSession; +import org.apache.qpid.server.queue.QueueEntry; public interface ProtocolOutputConverter { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/output/ProtocolOutputConverterImpl.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/output/ProtocolOutputConverterImpl.java new file mode 100644 index 0000000000..cfdcf7fb43 --- /dev/null +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/output/ProtocolOutputConverterImpl.java @@ -0,0 +1,413 @@ +package org.apache.qpid.server.output; +/* + * + * 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. + * + */ + +import org.apache.qpid.AMQException; +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.AMQShortString; +import org.apache.qpid.framing.BasicCancelOkBody; +import org.apache.qpid.framing.BasicContentHeaderProperties; +import org.apache.qpid.framing.BasicGetOkBody; +import org.apache.qpid.framing.BasicReturnBody; +import org.apache.qpid.framing.ContentHeaderBody; +import org.apache.qpid.framing.MethodRegistry; +import org.apache.qpid.framing.abstraction.MessagePublishInfo; +import org.apache.qpid.protocol.AMQVersionAwareProtocolSession; +import org.apache.qpid.server.message.AMQMessage; +import org.apache.qpid.server.message.MessageContentSource; +import org.apache.qpid.server.message.MessageTransferMessage; +import org.apache.qpid.server.protocol.AMQProtocolSession; +import org.apache.qpid.server.queue.QueueEntry; +import org.apache.qpid.transport.DeliveryProperties; + +import java.io.DataOutput; +import java.io.IOException; +import java.nio.ByteBuffer; + +class ProtocolOutputConverterImpl implements ProtocolOutputConverter +{ + private static final int BASIC_CLASS_ID = 60; + + private final MethodRegistry _methodRegistry; + private final AMQProtocolSession _protocolSession; + + ProtocolOutputConverterImpl(AMQProtocolSession session, MethodRegistry methodRegistry) + { + _protocolSession = session; + _methodRegistry = methodRegistry; + } + + + public AMQProtocolSession getProtocolSession() + { + return _protocolSession; + } + + public void writeDeliver(QueueEntry entry, int channelId, long deliveryTag, AMQShortString consumerTag) + throws AMQException + { + AMQBody deliverBody = createEncodedDeliverBody(entry, deliveryTag, consumerTag); + writeMessageDelivery(entry, channelId, deliverBody); + } + + + private ContentHeaderBody getContentHeaderBody(QueueEntry entry) + throws AMQException + { + if(entry.getMessage() instanceof AMQMessage) + { + return ((AMQMessage)entry.getMessage()).getContentHeaderBody(); + } + else + { + final MessageTransferMessage message = (MessageTransferMessage) entry.getMessage(); + BasicContentHeaderProperties props = HeaderPropertiesConverter.convert(message, entry.getQueue().getVirtualHost()); + ContentHeaderBody chb = new ContentHeaderBody(props, BASIC_CLASS_ID); + chb.setBodySize(message.getSize()); + return chb; + } + } + + + private void writeMessageDelivery(QueueEntry entry, int channelId, AMQBody deliverBody) + throws AMQException + { + writeMessageDelivery(entry.getMessage(), getContentHeaderBody(entry), channelId, deliverBody); + } + + private void writeMessageDelivery(MessageContentSource message, ContentHeaderBody contentHeaderBody, int channelId, AMQBody deliverBody) + throws AMQException + { + + + int bodySize = (int) message.getSize(); + + if(bodySize == 0) + { + SmallCompositeAMQBodyBlock compositeBlock = new SmallCompositeAMQBodyBlock(channelId, deliverBody, + contentHeaderBody); + + writeFrame(compositeBlock); + } + else + { + int maxBodySize = (int) getProtocolSession().getMaxFrameSize() - AMQFrame.getFrameOverhead(); + + + int capacity = bodySize > maxBodySize ? maxBodySize : bodySize; + + int writtenSize = capacity; + + AMQBody firstContentBody = new MessageContentSourceBody(message,0,capacity); + + CompositeAMQBodyBlock + compositeBlock = new CompositeAMQBodyBlock(channelId, deliverBody, contentHeaderBody, firstContentBody); + writeFrame(compositeBlock); + + while(writtenSize < bodySize) + { + capacity = bodySize - writtenSize > maxBodySize ? maxBodySize : bodySize - writtenSize; + MessageContentSourceBody body = new MessageContentSourceBody(message, writtenSize, capacity); + writtenSize += capacity; + + writeFrame(new AMQFrame(channelId, body)); + } + } + } + + private class MessageContentSourceBody implements AMQBody + { + public static final byte TYPE = 3; + private int _length; + private MessageContentSource _message; + private int _offset; + + public MessageContentSourceBody(MessageContentSource message, int offset, int length) + { + _message = message; + _offset = offset; + _length = length; + } + + public byte getFrameType() + { + return TYPE; + } + + public int getSize() + { + return _length; + } + + public void writePayload(DataOutput buffer) throws IOException + { + ByteBuffer buf = _message.getContent(_offset, _length); + + if(buf.hasArray()) + { + buffer.write(buf.array(), buf.arrayOffset()+buf.position(), buf.remaining()); + } + else + { + + byte[] data = new byte[_length]; + + buf.get(data); + + buffer.write(data); + } + } + + public void handle(int channelId, AMQVersionAwareProtocolSession amqProtocolSession) throws AMQException + { + throw new UnsupportedOperationException(); + } + } + + public void writeGetOk(QueueEntry entry, int channelId, long deliveryTag, int queueSize) throws AMQException + { + AMQBody deliver = createEncodedGetOkBody(entry, deliveryTag, queueSize); + writeMessageDelivery(entry, channelId, deliver); + } + + + private AMQBody createEncodedDeliverBody(QueueEntry entry, + final long deliveryTag, + final AMQShortString consumerTag) + throws AMQException + { + + final AMQShortString exchangeName; + final AMQShortString routingKey; + + if(entry.getMessage() instanceof AMQMessage) + { + final AMQMessage message = (AMQMessage) entry.getMessage(); + final MessagePublishInfo pb = message.getMessagePublishInfo(); + exchangeName = pb.getExchange(); + routingKey = pb.getRoutingKey(); + } + else + { + MessageTransferMessage message = (MessageTransferMessage) entry.getMessage(); + DeliveryProperties delvProps = message.getHeader().getDeliveryProperties(); + exchangeName = (delvProps == null || delvProps.getExchange() == null) ? null : new AMQShortString(delvProps.getExchange()); + routingKey = (delvProps == null || delvProps.getRoutingKey() == null) ? null : new AMQShortString(delvProps.getRoutingKey()); + } + + final boolean isRedelivered = entry.isRedelivered(); + + final AMQBody returnBlock = new AMQBody() + { + + private AMQBody _underlyingBody; + + public AMQBody createAMQBody() + { + return _methodRegistry.createBasicDeliverBody(consumerTag, + deliveryTag, + isRedelivered, + exchangeName, + routingKey); + + + + + + } + + public byte getFrameType() + { + return AMQMethodBody.TYPE; + } + + public int getSize() + { + if(_underlyingBody == null) + { + _underlyingBody = createAMQBody(); + } + return _underlyingBody.getSize(); + } + + public void writePayload(DataOutput buffer) throws IOException + { + if(_underlyingBody == null) + { + _underlyingBody = createAMQBody(); + } + _underlyingBody.writePayload(buffer); + } + + public void handle(final int channelId, final AMQVersionAwareProtocolSession amqMinaProtocolSession) + throws AMQException + { + throw new AMQException("This block should never be dispatched!"); + } + }; + return returnBlock; + } + + private AMQBody createEncodedGetOkBody(QueueEntry entry, long deliveryTag, int queueSize) + throws AMQException + { + final AMQShortString exchangeName; + final AMQShortString routingKey; + + if(entry.getMessage() instanceof AMQMessage) + { + final AMQMessage message = (AMQMessage) entry.getMessage(); + final MessagePublishInfo pb = message.getMessagePublishInfo(); + exchangeName = pb.getExchange(); + routingKey = pb.getRoutingKey(); + } + else + { + MessageTransferMessage message = (MessageTransferMessage) entry.getMessage(); + DeliveryProperties delvProps = message.getHeader().getDeliveryProperties(); + exchangeName = (delvProps == null || delvProps.getExchange() == null) ? null : new AMQShortString(delvProps.getExchange()); + routingKey = (delvProps == null || delvProps.getRoutingKey() == null) ? null : new AMQShortString(delvProps.getRoutingKey()); + } + + final boolean isRedelivered = entry.isRedelivered(); + + BasicGetOkBody getOkBody = + _methodRegistry.createBasicGetOkBody(deliveryTag, + isRedelivered, + exchangeName, + routingKey, + queueSize); + + return getOkBody; + } + + public byte getProtocolMinorVersion() + { + return _protocolSession.getProtocolMinorVersion(); + } + + public byte getProtocolMajorVersion() + { + return getProtocolSession().getProtocolMajorVersion(); + } + + private AMQBody createEncodedReturnFrame(MessagePublishInfo messagePublishInfo, + int replyCode, + AMQShortString replyText) throws AMQException + { + + BasicReturnBody basicReturnBody = + _methodRegistry.createBasicReturnBody(replyCode, + replyText, + messagePublishInfo.getExchange(), + messagePublishInfo.getRoutingKey()); + + + return basicReturnBody; + } + + public void writeReturn(MessagePublishInfo messagePublishInfo, ContentHeaderBody header, MessageContentSource message, int channelId, int replyCode, AMQShortString replyText) + throws AMQException + { + + AMQBody returnFrame = createEncodedReturnFrame(messagePublishInfo, replyCode, replyText); + + writeMessageDelivery(message, header, channelId, returnFrame); + } + + + public void writeFrame(AMQDataBlock block) + { + getProtocolSession().writeFrame(block); + } + + + public void confirmConsumerAutoClose(int channelId, AMQShortString consumerTag) + { + + BasicCancelOkBody basicCancelOkBody = _methodRegistry.createBasicCancelOkBody(consumerTag); + writeFrame(basicCancelOkBody.generateFrame(channelId)); + + } + + + public static final class CompositeAMQBodyBlock extends AMQDataBlock + { + public static final int OVERHEAD = 3 * AMQFrame.getFrameOverhead(); + + private final AMQBody _methodBody; + private final AMQBody _headerBody; + private final AMQBody _contentBody; + private final int _channel; + + + public CompositeAMQBodyBlock(int channel, AMQBody methodBody, AMQBody headerBody, AMQBody contentBody) + { + _channel = channel; + _methodBody = methodBody; + _headerBody = headerBody; + _contentBody = contentBody; + + } + + public long getSize() + { + return OVERHEAD + _methodBody.getSize() + _headerBody.getSize() + _contentBody.getSize(); + } + + public void writePayload(DataOutput buffer) throws IOException + { + AMQFrame.writeFrames(buffer, _channel, _methodBody, _headerBody, _contentBody); + } + } + + public static final class SmallCompositeAMQBodyBlock extends AMQDataBlock + { + public static final int OVERHEAD = 2 * AMQFrame.getFrameOverhead(); + + private final AMQBody _methodBody; + private final AMQBody _headerBody; + private final int _channel; + + + public SmallCompositeAMQBodyBlock(int channel, AMQBody methodBody, AMQBody headerBody) + { + _channel = channel; + _methodBody = methodBody; + _headerBody = headerBody; + + } + + public long getSize() + { + return OVERHEAD + _methodBody.getSize() + _headerBody.getSize() ; + } + + public void writePayload(DataOutput buffer) throws IOException + { + AMQFrame.writeFrames(buffer, _channel, _methodBody, _headerBody); + } + } + +} \ No newline at end of file diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/output/ProtocolOutputConverterRegistry.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/output/ProtocolOutputConverterRegistry.java index dbefeb61f2..dcbfd89298 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/output/ProtocolOutputConverterRegistry.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/output/ProtocolOutputConverterRegistry.java @@ -26,12 +26,13 @@ */ package org.apache.qpid.server.output; +import org.apache.qpid.framing.MethodRegistry; +import org.apache.qpid.framing.ProtocolVersion; import org.apache.qpid.server.output.ProtocolOutputConverter.Factory; import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.framing.ProtocolVersion; -import java.util.Map; import java.util.HashMap; +import java.util.Map; public class ProtocolOutputConverterRegistry { @@ -42,15 +43,19 @@ public class ProtocolOutputConverterRegistry static { - register(ProtocolVersion.v8_0, org.apache.qpid.server.output.amqp0_8.ProtocolOutputConverterImpl.getInstanceFactory()); - register(ProtocolVersion.v0_9, org.apache.qpid.server.output.amqp0_9.ProtocolOutputConverterImpl.getInstanceFactory()); - register(ProtocolVersion.v0_91, org.apache.qpid.server.output.amqp0_9_1.ProtocolOutputConverterImpl.getInstanceFactory()); + register(ProtocolVersion.v8_0); + register(ProtocolVersion.v0_9); + register(ProtocolVersion.v0_91); } - private static void register(ProtocolVersion version, Factory converter) + private ProtocolOutputConverterRegistry() + { + } + + private static void register(ProtocolVersion version) { - _registry.put(version,converter); + _registry.put(version,new ConverterFactory(version)); } @@ -58,4 +63,28 @@ public class ProtocolOutputConverterRegistry { return _registry.get(session.getProtocolVersion()).newInstance(session); } + + private static class ConverterFactory implements Factory + { + private ProtocolVersion _protocolVersion; + private MethodRegistry _methodRegistry; + private int _classId; + + public ConverterFactory(ProtocolVersion pv) + { + _protocolVersion = pv; + + } + + public synchronized ProtocolOutputConverter newInstance(AMQProtocolSession session) + { + if(_methodRegistry == null) + { + + _methodRegistry = MethodRegistry.getMethodRegistry(_protocolVersion); + + } + return new ProtocolOutputConverterImpl(session, _methodRegistry); + } + } } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/output/amqp0_8/ProtocolOutputConverterImpl.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/output/amqp0_8/ProtocolOutputConverterImpl.java deleted file mode 100644 index 1e62e5e9ca..0000000000 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/output/amqp0_8/ProtocolOutputConverterImpl.java +++ /dev/null @@ -1,420 +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. - * - */ - -/* - * This file is auto-generated by Qpid Gentools v.0.1 - do not modify. - * Supported AMQP versions: - * 8-0 - */ -package org.apache.qpid.server.output.amqp0_8; - -import org.apache.qpid.protocol.AMQVersionAwareProtocolSession; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.message.AMQMessage; -import org.apache.qpid.server.queue.QueueEntry; -import org.apache.qpid.server.output.ProtocolOutputConverter; -import org.apache.qpid.server.output.HeaderPropertiesConverter; -import org.apache.qpid.server.message.MessageContentSource; -import org.apache.qpid.server.message.MessageTransferMessage; -import org.apache.qpid.framing.*; -import org.apache.qpid.framing.abstraction.MessagePublishInfo; -import org.apache.qpid.AMQException; -import org.apache.qpid.transport.DeliveryProperties; - -import java.io.DataOutput; -import java.io.IOException; - -public class ProtocolOutputConverterImpl implements ProtocolOutputConverter -{ - - private static final MethodRegistry METHOD_REGISTRY = MethodRegistry.getMethodRegistry(ProtocolVersion.v8_0); - - public static Factory getInstanceFactory() - { - return new Factory() - { - - public ProtocolOutputConverter newInstance(AMQProtocolSession session) - { - return new ProtocolOutputConverterImpl(session); - } - }; - } - - - private final AMQProtocolSession _protocolSession; - - private ProtocolOutputConverterImpl(AMQProtocolSession session) - { - _protocolSession = session; - } - - - public AMQProtocolSession getProtocolSession() - { - return _protocolSession; - } - - public void writeDeliver(QueueEntry entry, int channelId, long deliveryTag, AMQShortString consumerTag) - throws AMQException - { - AMQBody deliverBody = createEncodedDeliverBody(entry, deliveryTag, consumerTag); - writeMessageDelivery(entry, channelId, deliverBody); - } - - - private ContentHeaderBody getContentHeaderBody(QueueEntry entry) - throws AMQException - { - if(entry.getMessage() instanceof AMQMessage) - { - return ((AMQMessage)entry.getMessage()).getContentHeaderBody(); - } - else - { - final MessageTransferMessage message = (MessageTransferMessage) entry.getMessage(); - BasicContentHeaderProperties props = HeaderPropertiesConverter.convert(message, entry.getQueue().getVirtualHost()); - ContentHeaderBody chb = new ContentHeaderBody(props, org.apache.qpid.framing.amqp_8_0.BasicGetBodyImpl.CLASS_ID); - chb.bodySize = message.getSize(); - return chb; - } - } - - - private void writeMessageDelivery(QueueEntry entry, int channelId, AMQBody deliverBody) - throws AMQException - { - writeMessageDelivery(entry.getMessage(), getContentHeaderBody(entry), channelId, deliverBody); - } - - private void writeMessageDelivery(MessageContentSource message, ContentHeaderBody contentHeaderBody, int channelId, AMQBody deliverBody) - throws AMQException - { - - - int bodySize = (int) message.getSize(); - - if(bodySize == 0) - { - SmallCompositeAMQBodyBlock compositeBlock = new SmallCompositeAMQBodyBlock(channelId, deliverBody, - contentHeaderBody); - - writeFrame(compositeBlock); - } - else - { - int maxBodySize = (int) getProtocolSession().getMaxFrameSize() - AMQFrame.getFrameOverhead(); - - - int capacity = bodySize > maxBodySize ? maxBodySize : bodySize; - - int writtenSize = capacity; - - AMQBody firstContentBody = new MessageContentSourceBody(message,0,capacity); - - CompositeAMQBodyBlock - compositeBlock = new CompositeAMQBodyBlock(channelId, deliverBody, contentHeaderBody, firstContentBody); - writeFrame(compositeBlock); - - while(writtenSize < bodySize) - { - capacity = bodySize - writtenSize > maxBodySize ? maxBodySize : bodySize - writtenSize; - MessageContentSourceBody body = new MessageContentSourceBody(message, writtenSize, capacity); - writtenSize += capacity; - - writeFrame(new AMQFrame(channelId, body)); - } - } - } - - private class MessageContentSourceBody implements AMQBody - { - public static final byte TYPE = 3; - private int _length; - private MessageContentSource _message; - private int _offset; - - public MessageContentSourceBody(MessageContentSource message, int offset, int length) - { - _message = message; - _offset = offset; - _length = length; - } - - public byte getFrameType() - { - return TYPE; - } - - public int getSize() - { - return _length; - } - - public void writePayload(DataOutput buffer) throws IOException - { - byte[] data = new byte[_length]; - - _message.getContent(java.nio.ByteBuffer.wrap(data), _offset); - - buffer.write(data); - } - - public void handle(int channelId, AMQVersionAwareProtocolSession amqProtocolSession) throws AMQException - { - throw new UnsupportedOperationException(); - } - } - - private AMQDataBlock createContentHeaderBlock(final int channelId, final ContentHeaderBody contentHeaderBody) - { - - AMQDataBlock contentHeader = ContentHeaderBody.createAMQFrame(channelId, - contentHeaderBody); - return contentHeader; - } - - - public void writeGetOk(QueueEntry entry, int channelId, long deliveryTag, int queueSize) throws AMQException - { - AMQBody deliver = createEncodedGetOkBody(entry, deliveryTag, queueSize); - writeMessageDelivery(entry, channelId, deliver); - } - - - private AMQBody createEncodedDeliverBody(QueueEntry entry, - final long deliveryTag, - final AMQShortString consumerTag) - throws AMQException - { - - final AMQShortString exchangeName; - final AMQShortString routingKey; - - if(entry.getMessage() instanceof AMQMessage) - { - final AMQMessage message = (AMQMessage) entry.getMessage(); - final MessagePublishInfo pb = message.getMessagePublishInfo(); - exchangeName = pb.getExchange(); - routingKey = pb.getRoutingKey(); - } - else - { - MessageTransferMessage message = (MessageTransferMessage) entry.getMessage(); - DeliveryProperties delvProps = message.getHeader().getDeliveryProperties(); - exchangeName = (delvProps == null || delvProps.getExchange() == null) ? null : new AMQShortString(delvProps.getExchange()); - routingKey = (delvProps == null || delvProps.getRoutingKey() == null) ? null : new AMQShortString(delvProps.getRoutingKey()); - } - - final boolean isRedelivered = entry.isRedelivered(); - - final AMQBody returnBlock = new AMQBody() - { - - public AMQBody _underlyingBody; - - public AMQBody createAMQBody() - { - return METHOD_REGISTRY.createBasicDeliverBody(consumerTag, - deliveryTag, - isRedelivered, - exchangeName, - routingKey); - - - - - - } - - public byte getFrameType() - { - return AMQMethodBody.TYPE; - } - - public int getSize() - { - if(_underlyingBody == null) - { - _underlyingBody = createAMQBody(); - } - return _underlyingBody.getSize(); - } - - public void writePayload(DataOutput buffer) throws IOException - { - if(_underlyingBody == null) - { - _underlyingBody = createAMQBody(); - } - _underlyingBody.writePayload(buffer); - } - - public void handle(final int channelId, final AMQVersionAwareProtocolSession amqMinaProtocolSession) - throws AMQException - { - throw new AMQException("This block should never be dispatched!"); - } - }; - return returnBlock; - } - - private AMQBody createEncodedGetOkBody(QueueEntry entry, long deliveryTag, int queueSize) - throws AMQException - { - final AMQShortString exchangeName; - final AMQShortString routingKey; - - if(entry.getMessage() instanceof AMQMessage) - { - final AMQMessage message = (AMQMessage) entry.getMessage(); - final MessagePublishInfo pb = message.getMessagePublishInfo(); - exchangeName = pb.getExchange(); - routingKey = pb.getRoutingKey(); - } - else - { - MessageTransferMessage message = (MessageTransferMessage) entry.getMessage(); - DeliveryProperties delvProps = message.getHeader().getDeliveryProperties(); - exchangeName = (delvProps == null || delvProps.getExchange() == null) ? null : new AMQShortString(delvProps.getExchange()); - routingKey = (delvProps == null || delvProps.getRoutingKey() == null) ? null : new AMQShortString(delvProps.getRoutingKey()); - } - - final boolean isRedelivered = entry.isRedelivered(); - - BasicGetOkBody getOkBody = - METHOD_REGISTRY.createBasicGetOkBody(deliveryTag, - isRedelivered, - exchangeName, - routingKey, - queueSize); - - return getOkBody; - } - - public byte getProtocolMinorVersion() - { - return getProtocolSession().getProtocolMinorVersion(); - } - - public byte getProtocolMajorVersion() - { - return getProtocolSession().getProtocolMajorVersion(); - } - - private AMQBody createEncodedReturnFrame(MessagePublishInfo messagePublishInfo, - int replyCode, - AMQShortString replyText) throws AMQException - { - - BasicReturnBody basicReturnBody = - METHOD_REGISTRY.createBasicReturnBody(replyCode, - replyText, - messagePublishInfo.getExchange(), - messagePublishInfo.getRoutingKey()); - - - return basicReturnBody; - } - - public void writeReturn(MessagePublishInfo messagePublishInfo, ContentHeaderBody header, MessageContentSource message, int channelId, int replyCode, AMQShortString replyText) - throws AMQException - { - - AMQBody returnFrame = createEncodedReturnFrame(messagePublishInfo, replyCode, replyText); - - writeMessageDelivery(message, header, channelId, returnFrame); - } - - - public void writeFrame(AMQDataBlock block) - { - getProtocolSession().writeFrame(block); - } - - - public void confirmConsumerAutoClose(int channelId, AMQShortString consumerTag) - { - - BasicCancelOkBody basicCancelOkBody = METHOD_REGISTRY.createBasicCancelOkBody(consumerTag); - writeFrame(basicCancelOkBody.generateFrame(channelId)); - - } - - - public static final class CompositeAMQBodyBlock extends AMQDataBlock - { - public static final int OVERHEAD = 3 * AMQFrame.getFrameOverhead(); - - private final AMQBody _methodBody; - private final AMQBody _headerBody; - private final AMQBody _contentBody; - private final int _channel; - - - public CompositeAMQBodyBlock(int channel, AMQBody methodBody, AMQBody headerBody, AMQBody contentBody) - { - _channel = channel; - _methodBody = methodBody; - _headerBody = headerBody; - _contentBody = contentBody; - - } - - public long getSize() - { - return OVERHEAD + _methodBody.getSize() + _headerBody.getSize() + _contentBody.getSize(); - } - - public void writePayload(DataOutput buffer) throws IOException - { - AMQFrame.writeFrames(buffer, _channel, _methodBody, _headerBody, _contentBody); - } - } - - public static final class SmallCompositeAMQBodyBlock extends AMQDataBlock - { - public static final int OVERHEAD = 2 * AMQFrame.getFrameOverhead(); - - private final AMQBody _methodBody; - private final AMQBody _headerBody; - private final int _channel; - - - public SmallCompositeAMQBodyBlock(int channel, AMQBody methodBody, AMQBody headerBody) - { - _channel = channel; - _methodBody = methodBody; - _headerBody = headerBody; - - } - - public long getSize() - { - return OVERHEAD + _methodBody.getSize() + _headerBody.getSize() ; - } - - public void writePayload(DataOutput buffer) throws IOException - { - AMQFrame.writeFrames(buffer, _channel, _methodBody, _headerBody); - } - } -} diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/output/amqp0_9/ProtocolOutputConverterImpl.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/output/amqp0_9/ProtocolOutputConverterImpl.java deleted file mode 100644 index 78507b0cf2..0000000000 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/output/amqp0_9/ProtocolOutputConverterImpl.java +++ /dev/null @@ -1,418 +0,0 @@ -package org.apache.qpid.server.output.amqp0_9; -/* - * - * 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. - * - */ - -import org.apache.qpid.server.output.ProtocolOutputConverter; -import org.apache.qpid.server.output.HeaderPropertiesConverter; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.message.AMQMessage; -import org.apache.qpid.server.queue.QueueEntry; -import org.apache.qpid.server.message.MessageContentSource; -import org.apache.qpid.server.message.MessageTransferMessage; -import org.apache.qpid.framing.*; -import org.apache.qpid.framing.amqp_0_9.BasicGetBodyImpl; -import org.apache.qpid.framing.abstraction.MessagePublishInfo; -import org.apache.qpid.AMQException; -import org.apache.qpid.transport.DeliveryProperties; -import org.apache.qpid.protocol.AMQVersionAwareProtocolSession; - -import java.io.DataOutput; -import java.io.IOException; -import java.nio.ByteBuffer; - -public class ProtocolOutputConverterImpl implements ProtocolOutputConverter -{ - private static final MethodRegistry METHOD_REGISTRY = MethodRegistry.getMethodRegistry(ProtocolVersion.v0_9); - - - public static Factory getInstanceFactory() - { - return new Factory() - { - - public ProtocolOutputConverter newInstance(AMQProtocolSession session) - { - return new ProtocolOutputConverterImpl(session); - } - }; - } - - private final AMQProtocolSession _protocolSession; - - private ProtocolOutputConverterImpl(AMQProtocolSession session) - { - _protocolSession = session; - } - - - public AMQProtocolSession getProtocolSession() - { - return _protocolSession; - } - - public void writeDeliver(QueueEntry entry, int channelId, long deliveryTag, AMQShortString consumerTag) - throws AMQException - { - AMQBody deliverBody = createEncodedDeliverBody(entry, deliveryTag, consumerTag); - writeMessageDelivery(entry, channelId, deliverBody); - } - - - private ContentHeaderBody getContentHeaderBody(QueueEntry entry) - throws AMQException - { - if(entry.getMessage() instanceof AMQMessage) - { - return ((AMQMessage)entry.getMessage()).getContentHeaderBody(); - } - else - { - final MessageTransferMessage message = (MessageTransferMessage) entry.getMessage(); - BasicContentHeaderProperties props = HeaderPropertiesConverter.convert(message, entry.getQueue().getVirtualHost()); - ContentHeaderBody chb = new ContentHeaderBody(props, BasicGetBodyImpl.CLASS_ID); - chb.bodySize = message.getSize(); - return chb; - } - } - - - private void writeMessageDelivery(QueueEntry entry, int channelId, AMQBody deliverBody) - throws AMQException - { - writeMessageDelivery(entry.getMessage(), getContentHeaderBody(entry), channelId, deliverBody); - } - - private void writeMessageDelivery(MessageContentSource message, ContentHeaderBody contentHeaderBody, int channelId, AMQBody deliverBody) - throws AMQException - { - - - int bodySize = (int) message.getSize(); - - if(bodySize == 0) - { - SmallCompositeAMQBodyBlock compositeBlock = new SmallCompositeAMQBodyBlock(channelId, deliverBody, - contentHeaderBody); - - writeFrame(compositeBlock); - } - else - { - int maxBodySize = (int) getProtocolSession().getMaxFrameSize() - AMQFrame.getFrameOverhead(); - - - int capacity = bodySize > maxBodySize ? maxBodySize : bodySize; - - int writtenSize = capacity; - - AMQBody firstContentBody = new MessageContentSourceBody(message,0,capacity); - - - CompositeAMQBodyBlock - compositeBlock = new CompositeAMQBodyBlock(channelId, deliverBody, contentHeaderBody, firstContentBody); - writeFrame(compositeBlock); - - while(writtenSize < bodySize) - { - capacity = bodySize - writtenSize > maxBodySize ? maxBodySize : bodySize - writtenSize; - MessageContentSourceBody body = new MessageContentSourceBody(message, writtenSize, capacity); - writtenSize += capacity; - - writeFrame(new AMQFrame(channelId, body)); - } - } - } - - private class MessageContentSourceBody implements AMQBody - { - public static final byte TYPE = 3; - private int _length; - private MessageContentSource _message; - private int _offset; - - public MessageContentSourceBody(MessageContentSource message, int offset, int length) - { - _message = message; - _offset = offset; - _length = length; - } - - public byte getFrameType() - { - return TYPE; - } - - public int getSize() - { - return _length; - } - - public void writePayload(DataOutput buffer) throws IOException - { - byte[] data = new byte[_length]; - - _message.getContent(ByteBuffer.wrap(data), _offset); - - buffer.write(data); - } - - public void handle(int channelId, AMQVersionAwareProtocolSession amqProtocolSession) throws AMQException - { - throw new UnsupportedOperationException(); - } - } - - - private AMQDataBlock createContentHeaderBlock(final int channelId, final ContentHeaderBody contentHeaderBody) - { - - AMQDataBlock contentHeader = ContentHeaderBody.createAMQFrame(channelId, - contentHeaderBody); - return contentHeader; - } - - - public void writeGetOk(QueueEntry entry, int channelId, long deliveryTag, int queueSize) throws AMQException - { - AMQBody deliver = createEncodedGetOkBody(entry, deliveryTag, queueSize); - writeMessageDelivery(entry, channelId, deliver); - } - - - private AMQBody createEncodedDeliverBody(QueueEntry entry, - final long deliveryTag, - final AMQShortString consumerTag) - throws AMQException - { - - final AMQShortString exchangeName; - final AMQShortString routingKey; - - if(entry.getMessage() instanceof AMQMessage) - { - final AMQMessage message = (AMQMessage) entry.getMessage(); - final MessagePublishInfo pb = message.getMessagePublishInfo(); - exchangeName = pb.getExchange(); - routingKey = pb.getRoutingKey(); - } - else - { - MessageTransferMessage message = (MessageTransferMessage) entry.getMessage(); - DeliveryProperties delvProps = message.getHeader().getDeliveryProperties(); - exchangeName = (delvProps == null || delvProps.getExchange() == null) ? null : new AMQShortString(delvProps.getExchange()); - routingKey = (delvProps == null || delvProps.getRoutingKey() == null) ? null : new AMQShortString(delvProps.getRoutingKey()); - } - - final boolean isRedelivered = entry.isRedelivered(); - - final AMQBody returnBlock = new AMQBody() - { - - public AMQBody _underlyingBody; - - public AMQBody createAMQBody() - { - return METHOD_REGISTRY.createBasicDeliverBody(consumerTag, - deliveryTag, - isRedelivered, - exchangeName, - routingKey); - - - - - - } - - public byte getFrameType() - { - return AMQMethodBody.TYPE; - } - - public int getSize() - { - if(_underlyingBody == null) - { - _underlyingBody = createAMQBody(); - } - return _underlyingBody.getSize(); - } - - public void writePayload(DataOutput buffer) throws IOException - { - if(_underlyingBody == null) - { - _underlyingBody = createAMQBody(); - } - _underlyingBody.writePayload(buffer); - } - - public void handle(final int channelId, final AMQVersionAwareProtocolSession amqMinaProtocolSession) - throws AMQException - { - throw new AMQException("This block should never be dispatched!"); - } - }; - return returnBlock; - } - - private AMQBody createEncodedGetOkBody(QueueEntry entry, long deliveryTag, int queueSize) - throws AMQException - { - final AMQShortString exchangeName; - final AMQShortString routingKey; - - if(entry.getMessage() instanceof AMQMessage) - { - final AMQMessage message = (AMQMessage) entry.getMessage(); - final MessagePublishInfo pb = message.getMessagePublishInfo(); - exchangeName = pb.getExchange(); - routingKey = pb.getRoutingKey(); - } - else - { - MessageTransferMessage message = (MessageTransferMessage) entry.getMessage(); - DeliveryProperties delvProps = message.getHeader().getDeliveryProperties(); - exchangeName = (delvProps == null || delvProps.getExchange() == null) ? null : new AMQShortString(delvProps.getExchange()); - routingKey = (delvProps == null || delvProps.getRoutingKey() == null) ? null : new AMQShortString(delvProps.getRoutingKey()); - } - - final boolean isRedelivered = entry.isRedelivered(); - - BasicGetOkBody getOkBody = - METHOD_REGISTRY.createBasicGetOkBody(deliveryTag, - isRedelivered, - exchangeName, - routingKey, - queueSize); - - return getOkBody; - } - - public byte getProtocolMinorVersion() - { - return getProtocolSession().getProtocolMinorVersion(); - } - - public byte getProtocolMajorVersion() - { - return getProtocolSession().getProtocolMajorVersion(); - } - - private AMQBody createEncodedReturnFrame(MessagePublishInfo messagePublishInfo, - int replyCode, - AMQShortString replyText) throws AMQException - { - - BasicReturnBody basicReturnBody = - METHOD_REGISTRY.createBasicReturnBody(replyCode, - replyText, - messagePublishInfo.getExchange(), - messagePublishInfo.getRoutingKey()); - - - return basicReturnBody; - } - - public void writeReturn(MessagePublishInfo messagePublishInfo, ContentHeaderBody header, MessageContentSource message, int channelId, int replyCode, AMQShortString replyText) - throws AMQException - { - - AMQBody returnFrame = createEncodedReturnFrame(messagePublishInfo, replyCode, replyText); - - writeMessageDelivery(message, header, channelId, returnFrame); - } - - - public void writeFrame(AMQDataBlock block) - { - getProtocolSession().writeFrame(block); - } - - - public void confirmConsumerAutoClose(int channelId, AMQShortString consumerTag) - { - - BasicCancelOkBody basicCancelOkBody = METHOD_REGISTRY.createBasicCancelOkBody(consumerTag); - writeFrame(basicCancelOkBody.generateFrame(channelId)); - - } - - - public static final class CompositeAMQBodyBlock extends AMQDataBlock - { - public static final int OVERHEAD = 3 * AMQFrame.getFrameOverhead(); - - private final AMQBody _methodBody; - private final AMQBody _headerBody; - private final AMQBody _contentBody; - private final int _channel; - - - public CompositeAMQBodyBlock(int channel, AMQBody methodBody, AMQBody headerBody, AMQBody contentBody) - { - _channel = channel; - _methodBody = methodBody; - _headerBody = headerBody; - _contentBody = contentBody; - - } - - public long getSize() - { - return OVERHEAD + _methodBody.getSize() + _headerBody.getSize() + _contentBody.getSize(); - } - - public void writePayload(DataOutput buffer) throws IOException - { - AMQFrame.writeFrames(buffer, _channel, _methodBody, _headerBody, _contentBody); - } - } - - public static final class SmallCompositeAMQBodyBlock extends AMQDataBlock - { - public static final int OVERHEAD = 2 * AMQFrame.getFrameOverhead(); - - private final AMQBody _methodBody; - private final AMQBody _headerBody; - private final int _channel; - - - public SmallCompositeAMQBodyBlock(int channel, AMQBody methodBody, AMQBody headerBody) - { - _channel = channel; - _methodBody = methodBody; - _headerBody = headerBody; - - } - - public long getSize() - { - return OVERHEAD + _methodBody.getSize() + _headerBody.getSize() ; - } - - public void writePayload(DataOutput buffer) throws IOException - { - AMQFrame.writeFrames(buffer, _channel, _methodBody, _headerBody); - } - } - -} diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/output/amqp0_9_1/ProtocolOutputConverterImpl.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/output/amqp0_9_1/ProtocolOutputConverterImpl.java deleted file mode 100644 index 9102b6c651..0000000000 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/output/amqp0_9_1/ProtocolOutputConverterImpl.java +++ /dev/null @@ -1,425 +0,0 @@ -package org.apache.qpid.server.output.amqp0_9_1; -/* - * - * 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. - * - */ - -import org.apache.qpid.server.output.ProtocolOutputConverter; -import org.apache.qpid.server.output.HeaderPropertiesConverter; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.message.AMQMessage; -import org.apache.qpid.server.queue.QueueEntry; -import org.apache.qpid.server.message.MessageContentSource; -import org.apache.qpid.server.message.MessageTransferMessage; -import org.apache.qpid.framing.*; -import org.apache.qpid.framing.amqp_0_91.BasicGetBodyImpl; -import org.apache.qpid.framing.abstraction.MessagePublishInfo; -import org.apache.qpid.AMQException; -import org.apache.qpid.transport.DeliveryProperties; -import org.apache.qpid.protocol.AMQVersionAwareProtocolSession; - -import java.io.DataOutput; -import java.io.IOException; -import java.nio.ByteBuffer; - -public class ProtocolOutputConverterImpl implements ProtocolOutputConverter -{ - private static final MethodRegistry METHOD_REGISTRY = MethodRegistry.getMethodRegistry(ProtocolVersion.v0_91); - - public static Factory getInstanceFactory() - { - return new Factory() - { - - public ProtocolOutputConverter newInstance(AMQProtocolSession session) - { - return new ProtocolOutputConverterImpl(session); - } - }; - } - - private final AMQProtocolSession _protocolSession; - - private ProtocolOutputConverterImpl(AMQProtocolSession session) - { - _protocolSession = session; - } - - - public AMQProtocolSession getProtocolSession() - { - return _protocolSession; - } - - public void writeDeliver(QueueEntry entry, int channelId, long deliveryTag, AMQShortString consumerTag) - throws AMQException - { - AMQBody deliverBody = createEncodedDeliverBody(entry, deliveryTag, consumerTag); - writeMessageDelivery(entry, channelId, deliverBody); - } - - - private ContentHeaderBody getContentHeaderBody(QueueEntry entry) - throws AMQException - { - if(entry.getMessage() instanceof AMQMessage) - { - return ((AMQMessage)entry.getMessage()).getContentHeaderBody(); - } - else - { - final MessageTransferMessage message = (MessageTransferMessage) entry.getMessage(); - BasicContentHeaderProperties props = HeaderPropertiesConverter.convert(message, entry.getQueue().getVirtualHost()); - ContentHeaderBody chb = new ContentHeaderBody(props, BasicGetBodyImpl.CLASS_ID); - chb.bodySize = message.getSize(); - return chb; - } - } - - - private void writeMessageDelivery(QueueEntry entry, int channelId, AMQBody deliverBody) - throws AMQException - { - writeMessageDelivery(entry.getMessage(), getContentHeaderBody(entry), channelId, deliverBody); - } - - private void writeMessageDelivery(MessageContentSource message, ContentHeaderBody contentHeaderBody, int channelId, AMQBody deliverBody) - throws AMQException - { - - - int bodySize = (int) message.getSize(); - - if(bodySize == 0) - { - SmallCompositeAMQBodyBlock compositeBlock = new SmallCompositeAMQBodyBlock(channelId, deliverBody, - contentHeaderBody); - - writeFrame(compositeBlock); - } - else - { - int maxBodySize = (int) getProtocolSession().getMaxFrameSize() - AMQFrame.getFrameOverhead(); - - - int capacity = bodySize > maxBodySize ? maxBodySize : bodySize; - - int writtenSize = capacity; - - AMQBody firstContentBody = new MessageContentSourceBody(message,0,capacity); - - CompositeAMQBodyBlock - compositeBlock = new CompositeAMQBodyBlock(channelId, deliverBody, contentHeaderBody, firstContentBody); - writeFrame(compositeBlock); - - while(writtenSize < bodySize) - { - capacity = bodySize - writtenSize > maxBodySize ? maxBodySize : bodySize - writtenSize; - MessageContentSourceBody body = new MessageContentSourceBody(message, writtenSize, capacity); - writtenSize += capacity; - - writeFrame(new AMQFrame(channelId, body)); - } - } - } - - private class MessageContentSourceBody implements AMQBody - { - public static final byte TYPE = 3; - private int _length; - private MessageContentSource _message; - private int _offset; - - public MessageContentSourceBody(MessageContentSource message, int offset, int length) - { - _message = message; - _offset = offset; - _length = length; - } - - public byte getFrameType() - { - return TYPE; - } - - public int getSize() - { - return _length; - } - - public void writePayload(DataOutput buffer) throws IOException - { - ByteBuffer buf = _message.getContent(_offset, _length); - - if(buf.hasArray()) - { - buffer.write(buf.array(), buf.arrayOffset()+buf.position(), buf.remaining()); - } - else - { - - byte[] data = new byte[_length]; - - buf.get(data); - - buffer.write(data); - } - } - - public void handle(int channelId, AMQVersionAwareProtocolSession amqProtocolSession) throws AMQException - { - throw new UnsupportedOperationException(); - } - } - - private AMQDataBlock createContentHeaderBlock(final int channelId, final ContentHeaderBody contentHeaderBody) - { - - AMQDataBlock contentHeader = ContentHeaderBody.createAMQFrame(channelId, - contentHeaderBody); - return contentHeader; - } - - - public void writeGetOk(QueueEntry entry, int channelId, long deliveryTag, int queueSize) throws AMQException - { - AMQBody deliver = createEncodedGetOkBody(entry, deliveryTag, queueSize); - writeMessageDelivery(entry, channelId, deliver); - } - - - private AMQBody createEncodedDeliverBody(QueueEntry entry, - final long deliveryTag, - final AMQShortString consumerTag) - throws AMQException - { - - final AMQShortString exchangeName; - final AMQShortString routingKey; - - if(entry.getMessage() instanceof AMQMessage) - { - final AMQMessage message = (AMQMessage) entry.getMessage(); - final MessagePublishInfo pb = message.getMessagePublishInfo(); - exchangeName = pb.getExchange(); - routingKey = pb.getRoutingKey(); - } - else - { - MessageTransferMessage message = (MessageTransferMessage) entry.getMessage(); - DeliveryProperties delvProps = message.getHeader().getDeliveryProperties(); - exchangeName = (delvProps == null || delvProps.getExchange() == null) ? null : new AMQShortString(delvProps.getExchange()); - routingKey = (delvProps == null || delvProps.getRoutingKey() == null) ? null : new AMQShortString(delvProps.getRoutingKey()); - } - - final boolean isRedelivered = entry.isRedelivered(); - - final AMQBody returnBlock = new AMQBody() - { - - public AMQBody _underlyingBody; - - public AMQBody createAMQBody() - { - return METHOD_REGISTRY.createBasicDeliverBody(consumerTag, - deliveryTag, - isRedelivered, - exchangeName, - routingKey); - - - - - - } - - public byte getFrameType() - { - return AMQMethodBody.TYPE; - } - - public int getSize() - { - if(_underlyingBody == null) - { - _underlyingBody = createAMQBody(); - } - return _underlyingBody.getSize(); - } - - public void writePayload(DataOutput buffer) throws IOException - { - if(_underlyingBody == null) - { - _underlyingBody = createAMQBody(); - } - _underlyingBody.writePayload(buffer); - } - - public void handle(final int channelId, final AMQVersionAwareProtocolSession amqMinaProtocolSession) - throws AMQException - { - throw new AMQException("This block should never be dispatched!"); - } - }; - return returnBlock; - } - - private AMQBody createEncodedGetOkBody(QueueEntry entry, long deliveryTag, int queueSize) - throws AMQException - { - final AMQShortString exchangeName; - final AMQShortString routingKey; - - if(entry.getMessage() instanceof AMQMessage) - { - final AMQMessage message = (AMQMessage) entry.getMessage(); - final MessagePublishInfo pb = message.getMessagePublishInfo(); - exchangeName = pb.getExchange(); - routingKey = pb.getRoutingKey(); - } - else - { - MessageTransferMessage message = (MessageTransferMessage) entry.getMessage(); - DeliveryProperties delvProps = message.getHeader().getDeliveryProperties(); - exchangeName = (delvProps == null || delvProps.getExchange() == null) ? null : new AMQShortString(delvProps.getExchange()); - routingKey = (delvProps == null || delvProps.getRoutingKey() == null) ? null : new AMQShortString(delvProps.getRoutingKey()); - } - - final boolean isRedelivered = entry.isRedelivered(); - - BasicGetOkBody getOkBody = - METHOD_REGISTRY.createBasicGetOkBody(deliveryTag, - isRedelivered, - exchangeName, - routingKey, - queueSize); - - return getOkBody; - } - - public byte getProtocolMinorVersion() - { - return getProtocolSession().getProtocolMinorVersion(); - } - - public byte getProtocolMajorVersion() - { - return getProtocolSession().getProtocolMajorVersion(); - } - - private AMQBody createEncodedReturnFrame(MessagePublishInfo messagePublishInfo, - int replyCode, - AMQShortString replyText) throws AMQException - { - - BasicReturnBody basicReturnBody = - METHOD_REGISTRY.createBasicReturnBody(replyCode, - replyText, - messagePublishInfo.getExchange(), - messagePublishInfo.getRoutingKey()); - - - return basicReturnBody; - } - - public void writeReturn(MessagePublishInfo messagePublishInfo, ContentHeaderBody header, MessageContentSource message, int channelId, int replyCode, AMQShortString replyText) - throws AMQException - { - - AMQBody returnFrame = createEncodedReturnFrame(messagePublishInfo, replyCode, replyText); - - writeMessageDelivery(message, header, channelId, returnFrame); - } - - - public void writeFrame(AMQDataBlock block) - { - getProtocolSession().writeFrame(block); - } - - - public void confirmConsumerAutoClose(int channelId, AMQShortString consumerTag) - { - - BasicCancelOkBody basicCancelOkBody = METHOD_REGISTRY.createBasicCancelOkBody(consumerTag); - writeFrame(basicCancelOkBody.generateFrame(channelId)); - - } - - - public static final class CompositeAMQBodyBlock extends AMQDataBlock - { - public static final int OVERHEAD = 3 * AMQFrame.getFrameOverhead(); - - private final AMQBody _methodBody; - private final AMQBody _headerBody; - private final AMQBody _contentBody; - private final int _channel; - - - public CompositeAMQBodyBlock(int channel, AMQBody methodBody, AMQBody headerBody, AMQBody contentBody) - { - _channel = channel; - _methodBody = methodBody; - _headerBody = headerBody; - _contentBody = contentBody; - - } - - public long getSize() - { - return OVERHEAD + _methodBody.getSize() + _headerBody.getSize() + _contentBody.getSize(); - } - - public void writePayload(DataOutput buffer) throws IOException - { - AMQFrame.writeFrames(buffer, _channel, _methodBody, _headerBody, _contentBody); - } - } - - public static final class SmallCompositeAMQBodyBlock extends AMQDataBlock - { - public static final int OVERHEAD = 2 * AMQFrame.getFrameOverhead(); - - private final AMQBody _methodBody; - private final AMQBody _headerBody; - private final int _channel; - - - public SmallCompositeAMQBodyBlock(int channel, AMQBody methodBody, AMQBody headerBody) - { - _channel = channel; - _methodBody = methodBody; - _headerBody = headerBody; - - } - - public long getSize() - { - return OVERHEAD + _methodBody.getSize() + _headerBody.getSize() ; - } - - public void writePayload(DataOutput buffer) throws IOException - { - AMQFrame.writeFrames(buffer, _channel, _methodBody, _headerBody); - } - } - -} \ No newline at end of file diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/plugins/Activator.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/plugins/Activator.java index df72e87fd8..12e1eee9ca 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/plugins/Activator.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/plugins/Activator.java @@ -19,11 +19,12 @@ package org.apache.qpid.server.plugins; import org.apache.log4j.Logger; -import org.apache.qpid.server.configuration.ServerConfiguration; -import org.apache.qpid.server.registry.ApplicationRegistry; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; +import org.apache.qpid.server.configuration.ServerConfiguration; +import org.apache.qpid.server.registry.ApplicationRegistry; + public class Activator implements BundleActivator { private static final Logger _logger = Logger.getLogger(Activator.class); diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/plugins/OsgiSystemPackageUtil.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/plugins/OsgiSystemPackageUtil.java index 644f714c8c..d2bb3e037c 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/plugins/OsgiSystemPackageUtil.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/plugins/OsgiSystemPackageUtil.java @@ -18,11 +18,11 @@ */ package org.apache.qpid.server.plugins; +import org.osgi.framework.Version; + import java.util.Iterator; import java.util.Map; -import org.osgi.framework.Version; - /** * Utility class to convert a map of package name to version numbers into the string * with the format expected of a OSGi system package declaration: diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/plugins/Plugin.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/plugins/Plugin.java index 804a9d5027..6dcf688f2a 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/plugins/Plugin.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/plugins/Plugin.java @@ -19,6 +19,7 @@ package org.apache.qpid.server.plugins; import org.apache.commons.configuration.ConfigurationException; + import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin; public interface Plugin diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/plugins/PluginFactory.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/plugins/PluginFactory.java index bbf3e74a30..7ea2b95b89 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/plugins/PluginFactory.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/plugins/PluginFactory.java @@ -19,6 +19,7 @@ package org.apache.qpid.server.plugins; import org.apache.commons.configuration.ConfigurationException; + import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin; public interface PluginFactory

diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/plugins/PluginManager.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/plugins/PluginManager.java index dab6c3b231..880b1cca8d 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/plugins/PluginManager.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/plugins/PluginManager.java @@ -18,32 +18,17 @@ */ package org.apache.qpid.server.plugins; -import static org.apache.felix.framework.util.FelixConstants.SYSTEMBUNDLE_ACTIVATORS_PROP; -import static org.apache.felix.main.AutoProcessor.AUTO_DEPLOY_ACTION_PROPERY; -import static org.apache.felix.main.AutoProcessor.AUTO_DEPLOY_DIR_PROPERY; -import static org.apache.felix.main.AutoProcessor.AUTO_DEPLOY_INSTALL_VALUE; -import static org.apache.felix.main.AutoProcessor.AUTO_DEPLOY_START_VALUE; -import static org.apache.felix.main.AutoProcessor.process; -import static org.osgi.framework.Constants.FRAMEWORK_STORAGE; -import static org.osgi.framework.Constants.FRAMEWORK_STORAGE_CLEAN; -import static org.osgi.framework.Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT; -import static org.osgi.framework.Constants.FRAMEWORK_SYSTEMPACKAGES; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.IdentityHashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; - import org.apache.commons.configuration.ConfigurationException; import org.apache.felix.framework.Felix; import org.apache.felix.framework.util.StringMap; import org.apache.log4j.Logger; +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; +import org.osgi.framework.BundleException; +import org.osgi.framework.Version; +import org.osgi.framework.launch.Framework; +import org.osgi.util.tracker.ServiceTracker; + import org.apache.qpid.common.Closeable; import org.apache.qpid.common.QpidProperties; import org.apache.qpid.server.configuration.TopicConfiguration; @@ -54,8 +39,6 @@ import org.apache.qpid.server.configuration.plugins.SlowConsumerDetectionQueueCo import org.apache.qpid.server.exchange.ExchangeType; import org.apache.qpid.server.security.SecurityManager; import org.apache.qpid.server.security.SecurityPluginFactory; -import org.apache.qpid.server.security.access.plugins.AllowAll; -import org.apache.qpid.server.security.access.plugins.DenyAll; import org.apache.qpid.server.security.access.plugins.LegacyAccess; import org.apache.qpid.server.security.auth.manager.AuthenticationManagerPluginFactory; import org.apache.qpid.server.security.auth.manager.PrincipalDatabaseAuthenticationManager; @@ -64,12 +47,28 @@ import org.apache.qpid.server.virtualhost.plugins.VirtualHostPluginFactory; import org.apache.qpid.server.virtualhost.plugins.policies.TopicDeletePolicy; import org.apache.qpid.slowconsumerdetection.policies.SlowConsumerPolicyPluginFactory; import org.apache.qpid.util.FileUtils; -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; -import org.osgi.framework.BundleException; -import org.osgi.framework.Version; -import org.osgi.framework.launch.Framework; -import org.osgi.util.tracker.ServiceTracker; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +import static org.apache.felix.framework.util.FelixConstants.SYSTEMBUNDLE_ACTIVATORS_PROP; +import static org.apache.felix.main.AutoProcessor.AUTO_DEPLOY_ACTION_PROPERY; +import static org.apache.felix.main.AutoProcessor.AUTO_DEPLOY_DIR_PROPERY; +import static org.apache.felix.main.AutoProcessor.AUTO_DEPLOY_INSTALL_VALUE; +import static org.apache.felix.main.AutoProcessor.AUTO_DEPLOY_START_VALUE; +import static org.apache.felix.main.AutoProcessor.process; +import static org.osgi.framework.Constants.FRAMEWORK_STORAGE; +import static org.osgi.framework.Constants.FRAMEWORK_STORAGE_CLEAN; +import static org.osgi.framework.Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT; +import static org.osgi.framework.Constants.FRAMEWORK_SYSTEMPACKAGES; /** * Provides access to pluggable elements, such as exchanges @@ -146,16 +145,13 @@ public class PluginManager implements Closeable { // Store all non-OSGi plugins // A little gross that we have to add them here, but not all the plugins are OSGIfied - for (SecurityPluginFactory pluginFactory : Arrays.asList( - AllowAll.FACTORY, DenyAll.FACTORY, LegacyAccess.FACTORY)) + for (SecurityPluginFactory pluginFactory : Arrays.asList(LegacyAccess.FACTORY)) { _securityPlugins.put(pluginFactory.getPluginName(), pluginFactory); } for (ConfigurationPluginFactory configFactory : Arrays.asList( TopicConfiguration.FACTORY, SecurityManager.SecurityConfiguration.FACTORY, - AllowAll.AllowAllConfiguration.FACTORY, - DenyAll.DenyAllConfiguration.FACTORY, LegacyAccess.LegacyAccessConfiguration.FACTORY, new SlowConsumerDetectionConfigurationFactory(), new SlowConsumerDetectionPolicyConfigurationFactory(), @@ -254,6 +250,8 @@ public class PluginManager implements Closeable _logger.info("Using the specified external BundleContext"); } + // TODO save trackers in a map, keyed by class name + _exchangeTracker = new ServiceTracker(bundleContext, ExchangeType.class.getName(), null); _exchangeTracker.open(); _trackers.add(_exchangeTracker); diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQConnectionModel.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQConnectionModel.java index bc0d4e3bcc..5af3899890 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQConnectionModel.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQConnectionModel.java @@ -20,14 +20,14 @@ */ package org.apache.qpid.server.protocol; -import java.util.List; -import java.util.UUID; - import org.apache.qpid.AMQException; import org.apache.qpid.protocol.AMQConstant; import org.apache.qpid.server.logging.LogSubject; import org.apache.qpid.server.stats.StatisticsGatherer; +import java.util.List; +import java.util.UUID; + public interface AMQConnectionModel extends StatisticsGatherer { /** diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolEngine.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolEngine.java index 547f2440db..e9ad4ea8e0 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolEngine.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolEngine.java @@ -20,34 +20,15 @@ */ package org.apache.qpid.server.protocol; -import java.io.DataOutput; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.net.InetSocketAddress; -import java.net.SocketAddress; -import java.nio.ByteBuffer; -import java.security.Principal; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.CopyOnWriteArraySet; -import java.util.concurrent.atomic.AtomicBoolean; -import javax.management.JMException; -import javax.security.auth.Subject; -import javax.security.sasl.SaslServer; import org.apache.log4j.Logger; + import org.apache.qpid.AMQChannelException; import org.apache.qpid.AMQConnectionException; import org.apache.qpid.AMQException; import org.apache.qpid.AMQSecurityException; import org.apache.qpid.codec.AMQCodecFactory; -import org.apache.qpid.common.ClientProperties; import org.apache.qpid.framing.*; +import org.apache.qpid.properties.ConnectionStartProperties; import org.apache.qpid.protocol.AMQConstant; import org.apache.qpid.protocol.AMQMethodEvent; import org.apache.qpid.protocol.AMQMethodListener; @@ -83,13 +64,30 @@ import org.apache.qpid.server.virtualhost.VirtualHostRegistry; import org.apache.qpid.transport.Sender; import org.apache.qpid.transport.TransportException; import org.apache.qpid.transport.network.NetworkConnection; +import org.apache.qpid.util.BytesDataOutput; + +import javax.management.JMException; +import javax.security.auth.Subject; +import javax.security.sasl.SaslServer; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.SocketAddress; +import java.nio.ByteBuffer; +import java.security.Principal; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CopyOnWriteArraySet; +import java.util.concurrent.atomic.AtomicBoolean; public class AMQProtocolEngine implements ServerProtocolEngine, Managable, AMQProtocolSession, ConnectionConfig { private static final Logger _logger = Logger.getLogger(AMQProtocolEngine.class); - 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; @@ -97,7 +95,7 @@ public class AMQProtocolEngine implements ServerProtocolEngine, Managable, AMQPr private AMQShortString _contextKey; - private AMQShortString _clientVersion = null; + private String _clientVersion = null; private VirtualHost _virtualHost; @@ -119,7 +117,7 @@ public class AMQProtocolEngine implements ServerProtocolEngine, Managable, AMQPr private Object _lastSent; - protected volatile boolean _closed; + private volatile boolean _closed; // maximum number of channels this session should have private long _maxNoOfChannels = ApplicationRegistry.getInstance().getConfiguration().getMaxChannelCount(); @@ -134,9 +132,9 @@ public class AMQProtocolEngine implements ServerProtocolEngine, Managable, AMQPr private ProtocolOutputConverter _protocolOutputConverter; private Subject _authorizedSubject; private MethodDispatcher _dispatcher; - private ProtocolSessionIdentifier _sessionIdentifier; - private final long _sessionID; + private final long _connectionID; + private Object _reference = new Object(); private AMQPConnectionActor _actor; private LogSubject _logSubject; @@ -174,7 +172,7 @@ public class AMQProtocolEngine implements ServerProtocolEngine, Managable, AMQPr _codecFactory = new AMQCodecFactory(true, this); setNetworkConnection(network); - _sessionID = connectionId; + _connectionID = connectionId; _actor = new AMQPConnectionActor(this, virtualHostRegistry.getApplicationRegistry().getRootMessageLogger()); @@ -183,7 +181,7 @@ public class AMQProtocolEngine implements ServerProtocolEngine, Managable, AMQPr _configStore = virtualHostRegistry.getConfigStore(); _id = _configStore.createId(); - _actor.message(ConnectionMessages.OPEN(null, null, false, false)); + _actor.message(ConnectionMessages.OPEN(null, null, null, false, false, false)); _registry = virtualHostRegistry.getApplicationRegistry(); initialiseStatistics(); @@ -207,7 +205,7 @@ public class AMQProtocolEngine implements ServerProtocolEngine, Managable, AMQPr public long getSessionID() { - return _sessionID; + return _connectionID; } public LogActor getLogActor() @@ -369,7 +367,7 @@ public class AMQProtocolEngine implements ServerProtocolEngine, Managable, AMQPr try { // Log incomming protocol negotiation request - _actor.message(ConnectionMessages.OPEN(null, pi._protocolMajor + "-" + pi._protocolMinor, false, true)); + _actor.message(ConnectionMessages.OPEN(null, pi.getProtocolMajor() + "-" + pi.getProtocolMinor(), null, false, true, false)); ProtocolVersion pv = pi.checkVersion(); // Fails if not correct @@ -721,7 +719,7 @@ public class AMQProtocolEngine implements ServerProtocolEngine, Managable, AMQPr // However, due to the poor exception handling on the client. The client-user will be notified of the // InvalidArgument and if they then decide to close the session/connection then the there will be time // for that to occur i.e. a new close method be sent before the exeption handling can mark the session closed. - //removeChannel(channelId); + _closingChannelsList.remove(channelId); } @@ -922,31 +920,22 @@ public class AMQProtocolEngine implements ServerProtocolEngine, Managable, AMQPr _saslServer = saslServer; } - public FieldTable getClientProperties() - { - return _clientProperties; - } - public void setClientProperties(FieldTable clientProperties) { _clientProperties = clientProperties; if (_clientProperties != null) { - if (_clientProperties.getString(CLIENT_PROPERTIES_INSTANCE) != null) + _clientVersion = _clientProperties.getString(ConnectionStartProperties.VERSION_0_8); + + if (_clientProperties.getString(ConnectionStartProperties.CLIENT_ID_0_8) != null) { - String clientID = _clientProperties.getString(CLIENT_PROPERTIES_INSTANCE); + String clientID = _clientProperties.getString(ConnectionStartProperties.CLIENT_ID_0_8); setContextKey(new AMQShortString(clientID)); // Log the Opening of the connection for this client - _actor.message(ConnectionMessages.OPEN(clientID, _protocolVersion.toString(), true, true)); - } - - if (_clientProperties.getString(ClientProperties.version.toString()) != null) - { - _clientVersion = new AMQShortString(_clientProperties.getString(ClientProperties.version.toString())); + _actor.message(ConnectionMessages.OPEN(clientID, _protocolVersion.toString(), _clientVersion, true, true, true)); } } - _sessionIdentifier = new ProtocolSessionIdentifier(this); } private void setProtocolVersion(ProtocolVersion pv) @@ -982,11 +971,6 @@ public class AMQProtocolEngine implements ServerProtocolEngine, Managable, AMQPr return getMethodRegistry(); } - public Object getClientIdentifier() - { - return _network.getRemoteAddress(); - } - public VirtualHost getVirtualHost() { return _virtualHost; @@ -1155,14 +1139,9 @@ public class AMQProtocolEngine implements ServerProtocolEngine, Managable, AMQPr return _lastReceivedTime; } - public ProtocolSessionIdentifier getSessionIdentifier() - { - return _sessionIdentifier; - } - public String getClientVersion() { - return (_clientVersion == null) ? null : _clientVersion.toString(); + return _clientVersion; } public Boolean isIncoming() @@ -1357,6 +1336,11 @@ public class AMQProtocolEngine implements ServerProtocolEngine, Managable, AMQPr (Throwable) null)); } + public boolean isClosed() + { + return _closed; + } + public List getSessionModels() { List sessions = new ArrayList(); @@ -1457,30 +1441,6 @@ public class AMQProtocolEngine implements ServerProtocolEngine, Managable, AMQPr return getAuthorizedPrincipal().getName(); } - private static class ByteBufferOutputStream extends OutputStream - { - - - private final ByteBuffer _buf; - - public ByteBufferOutputStream(ByteBuffer buf) - { - _buf = buf; - } - - @Override - public void write(int b) throws IOException - { - _buf.put((byte) b); - } - - @Override - public void write(byte[] b, int off, int len) throws IOException - { - _buf.put(b, off, len); - } - } - public final class WriteDeliverMethod implements ClientDeliveryMethod { @@ -1501,158 +1461,8 @@ public class AMQProtocolEngine implements ServerProtocolEngine, Managable, AMQPr } - private static class BytesDataOutput implements DataOutput + public Object getReference() { - int _pos = 0; - byte[] _buf; - - public BytesDataOutput(byte[] buf) - { - _buf = buf; - } - - public void setBuffer(byte[] buf) - { - _buf = buf; - _pos = 0; - } - - public void reset() - { - _pos = 0; - } - - public int length() - { - return _pos; - } - - public void write(int b) - { - _buf[_pos++] = (byte) b; - } - - public void write(byte[] b) - { - System.arraycopy(b, 0, _buf, _pos, b.length); - _pos+=b.length; - } - - - public void write(byte[] b, int off, int len) - { - System.arraycopy(b, off, _buf, _pos, len); - _pos+=len; - - } - - public void writeBoolean(boolean v) - { - _buf[_pos++] = v ? (byte) 1 : (byte) 0; - } - - public void writeByte(int v) - { - _buf[_pos++] = (byte) v; - } - - public void writeShort(int v) - { - _buf[_pos++] = (byte) (v >>> 8); - _buf[_pos++] = (byte) v; - } - - public void writeChar(int v) - { - _buf[_pos++] = (byte) (v >>> 8); - _buf[_pos++] = (byte) v; - } - - public void writeInt(int v) - { - _buf[_pos++] = (byte) (v >>> 24); - _buf[_pos++] = (byte) (v >>> 16); - _buf[_pos++] = (byte) (v >>> 8); - _buf[_pos++] = (byte) v; - } - - public void writeLong(long v) - { - _buf[_pos++] = (byte) (v >>> 56); - _buf[_pos++] = (byte) (v >>> 48); - _buf[_pos++] = (byte) (v >>> 40); - _buf[_pos++] = (byte) (v >>> 32); - _buf[_pos++] = (byte) (v >>> 24); - _buf[_pos++] = (byte) (v >>> 16); - _buf[_pos++] = (byte) (v >>> 8); - _buf[_pos++] = (byte)v; - } - - public void writeFloat(float v) - { - writeInt(Float.floatToIntBits(v)); - } - - public void writeDouble(double v) - { - writeLong(Double.doubleToLongBits(v)); - } - - public void writeBytes(String s) - { - int len = s.length(); - for (int i = 0 ; i < len ; i++) - { - _buf[_pos++] = ((byte)s.charAt(i)); - } - } - - public void writeChars(String s) - { - int len = s.length(); - for (int i = 0 ; i < len ; i++) - { - int v = s.charAt(i); - _buf[_pos++] = (byte) (v >>> 8); - _buf[_pos++] = (byte) v; - } - } - - public void writeUTF(String s) - { - int strlen = s.length(); - - int pos = _pos; - _pos+=2; - - - for (int i = 0; i < strlen; i++) - { - int c = s.charAt(i); - if ((c >= 0x0001) && (c <= 0x007F)) - { - c = s.charAt(i); - _buf[_pos++] = (byte) c; - - } - else if (c > 0x07FF) - { - _buf[_pos++] = (byte) (0xE0 | ((c >> 12) & 0x0F)); - _buf[_pos++] = (byte) (0x80 | ((c >> 6) & 0x3F)); - _buf[_pos++] = (byte) (0x80 | (c & 0x3F)); - } - else - { - _buf[_pos++] = (byte) (0xC0 | ((c >> 6) & 0x1F)); - _buf[_pos++] = (byte) (0x80 | (c & 0x3F)); - } - } - - int len = _pos - (pos + 2); - - _buf[pos++] = (byte) (len >>> 8); - _buf[pos] = (byte) len; - } - + return _reference; } } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolSession.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolSession.java index dfba10750c..6cd5b21f89 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolSession.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolSession.java @@ -20,23 +20,25 @@ */ package org.apache.qpid.server.protocol; +import java.util.List; + import javax.security.auth.Subject; import javax.security.sasl.SaslServer; -import org.apache.qpid.AMQException; -import org.apache.qpid.common.ClientProperties; -import org.apache.qpid.framing.*; import org.apache.qpid.AMQConnectionException; +import org.apache.qpid.AMQException; +import org.apache.qpid.framing.AMQShortString; +import org.apache.qpid.framing.FieldTable; +import org.apache.qpid.framing.MethodDispatcher; +import org.apache.qpid.framing.MethodRegistry; import org.apache.qpid.protocol.AMQVersionAwareProtocolSession; import org.apache.qpid.server.AMQChannel; -import org.apache.qpid.server.security.AuthorizationHolder; import org.apache.qpid.server.logging.LogActor; import org.apache.qpid.server.output.ProtocolOutputConverter; +import org.apache.qpid.server.security.AuthorizationHolder; import org.apache.qpid.server.subscription.ClientDeliveryMethod; import org.apache.qpid.server.virtualhost.VirtualHost; -import java.util.List; - public interface AMQProtocolSession extends AMQVersionAwareProtocolSession, AuthorizationHolder, AMQConnectionModel { @@ -58,28 +60,6 @@ public interface AMQProtocolSession extends AMQVersionAwareProtocolSession, Auth long getLastReceivedTime(); - public static final class ProtocolSessionIdentifier - { - private final Object _sessionIdentifier; - private final Object _sessionInstance; - - ProtocolSessionIdentifier(AMQProtocolSession session) - { - _sessionIdentifier = session.getClientIdentifier(); - _sessionInstance = session.getClientProperties() == null ? null : session.getClientProperties().getObject(ClientProperties.instance.toAMQShortString()); - } - - public Object getSessionIdentifier() - { - return _sessionIdentifier; - } - - public Object getSessionInstance() - { - return _sessionInstance; - } - } - public static interface Task { public void doTask(AMQProtocolSession session) throws AMQException; @@ -190,12 +170,9 @@ public interface AMQProtocolSession extends AMQVersionAwareProtocolSession, Auth */ void setSaslServer(SaslServer saslServer); - - FieldTable getClientProperties(); - void setClientProperties(FieldTable clientProperties); - Object getClientIdentifier(); + Object getReference(); VirtualHost getVirtualHost(); @@ -215,8 +192,6 @@ public interface AMQProtocolSession extends AMQVersionAwareProtocolSession, Auth public MethodDispatcher getMethodDispatcher(); - public ProtocolSessionIdentifier getSessionIdentifier(); - String getClientVersion(); long getLastIoTime(); diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolSessionMBean.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolSessionMBean.java index 8d39420631..e70720600e 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolSessionMBean.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolSessionMBean.java @@ -22,7 +22,7 @@ * * Copyright (c) 2006 The Apache Software Foundation * - * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 * @@ -37,16 +37,6 @@ */ package org.apache.qpid.server.protocol; -import java.util.Date; -import java.util.List; -import javax.management.JMException; -import javax.management.MBeanException; -import javax.management.NotCompliantMBeanException; -import javax.management.openmbean.CompositeData; -import javax.management.openmbean.CompositeDataSupport; -import javax.management.openmbean.OpenDataException; -import javax.management.openmbean.TabularData; -import javax.management.openmbean.TabularDataSupport; import org.apache.qpid.AMQException; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.framing.ConnectionCloseBody; @@ -60,6 +50,17 @@ import org.apache.qpid.server.logging.actors.ManagementActor; import org.apache.qpid.server.management.AbstractAMQManagedConnectionObject; import org.apache.qpid.server.management.ManagedObject; +import javax.management.JMException; +import javax.management.MBeanException; +import javax.management.NotCompliantMBeanException; +import javax.management.openmbean.CompositeData; +import javax.management.openmbean.CompositeDataSupport; +import javax.management.openmbean.OpenDataException; +import javax.management.openmbean.TabularData; +import javax.management.openmbean.TabularDataSupport; +import java.util.Date; +import java.util.List; + /** * This MBean class implements the management interface. In order to make more attributes, operations and notifications * available over JMX simply augment the ManagedConnection interface and add the appropriate implementation here. @@ -91,7 +92,7 @@ public class AMQProtocolSessionMBean extends AbstractAMQManagedConnectionObject public String getVersion() { - return (_protocolSession.getClientVersion() == null) ? null : _protocolSession.getClientVersion().toString(); + return _protocolSession.getClientVersion(); } public Date getLastIoTime() @@ -132,7 +133,7 @@ public class AMQProtocolSessionMBean extends AbstractAMQManagedConnectionObject */ public void commitTransactions(int channelId) throws JMException { - CurrentActor.set(new ManagementActor(_logActor.getRootMessageLogger())); + CurrentActor.set(new ManagementActor(getLogActor().getRootMessageLogger())); try { AMQChannel channel = _protocolSession.getChannel(channelId); @@ -161,7 +162,7 @@ public class AMQProtocolSessionMBean extends AbstractAMQManagedConnectionObject */ public void rollbackTransactions(int channelId) throws JMException { - CurrentActor.set(new ManagementActor(_logActor.getRootMessageLogger())); + CurrentActor.set(new ManagementActor(getLogActor().getRootMessageLogger())); try { AMQChannel channel = _protocolSession.getChannel(channelId); @@ -240,7 +241,7 @@ public class AMQProtocolSessionMBean extends AbstractAMQManagedConnectionObject if (CurrentActor.get() == null) { removeActor = true; - CurrentActor.set(new ManagementActor(_logActor.getRootMessageLogger())); + CurrentActor.set(new ManagementActor(getLogActor().getRootMessageLogger())); } try diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQSessionModel.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQSessionModel.java index c55fe321fc..a69f2a74ee 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQSessionModel.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQSessionModel.java @@ -20,12 +20,20 @@ */ package org.apache.qpid.server.protocol; +import java.util.concurrent.ConcurrentSkipListSet; + import org.apache.qpid.AMQException; import org.apache.qpid.server.logging.LogSubject; +import org.apache.qpid.server.message.InboundMessage; import org.apache.qpid.server.queue.AMQQueue; import org.apache.qpid.server.queue.SimpleAMQQueue; -public interface AMQSessionModel +/** + * Session model interface. + * Extends {@link Comparable} to allow objects to be inserted into a {@link ConcurrentSkipListSet} + * when monitoring the blocking and blocking of queues/sessions in {@link SimpleAMQQueue}. + */ +public interface AMQSessionModel extends Comparable { public Object getID(); @@ -57,4 +65,7 @@ public interface AMQSessionModel void block(AMQQueue queue); void unblock(AMQQueue queue); + + + boolean onSameConnection(InboundMessage inbound); } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/protocol/MultiVersionProtocolEngine.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/protocol/MultiVersionProtocolEngine.java index a71d396919..ce20690f66 100755 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/protocol/MultiVersionProtocolEngine.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/protocol/MultiVersionProtocolEngine.java @@ -21,6 +21,11 @@ package org.apache.qpid.server.protocol; +import java.net.InetSocketAddress; +import java.net.SocketAddress; +import java.nio.ByteBuffer; +import java.util.Set; + import org.apache.log4j.Logger; import org.apache.qpid.protocol.ServerProtocolEngine; import org.apache.qpid.server.registry.IApplicationRegistry; @@ -29,10 +34,6 @@ import org.apache.qpid.transport.ConnectionDelegate; import org.apache.qpid.transport.Sender; import org.apache.qpid.transport.network.NetworkConnection; -import java.net.SocketAddress; -import java.nio.ByteBuffer; -import java.util.Set; - public class MultiVersionProtocolEngine implements ServerProtocolEngine { private static final Logger _logger = Logger.getLogger(MultiVersionProtocolEngine.class); @@ -44,29 +45,35 @@ public class MultiVersionProtocolEngine implements ServerProtocolEngine private IApplicationRegistry _appRegistry; private NetworkConnection _network; private Sender _sender; + private final AmqpProtocolVersion _defaultSupportedReply; private volatile ServerProtocolEngine _delegate = new SelfDelegateProtocolEngine(); - public MultiVersionProtocolEngine(IApplicationRegistry appRegistry, - String fqdn, - Set supported, - NetworkConnection network, - long id) + public MultiVersionProtocolEngine(final IApplicationRegistry appRegistry, + final Set supported, + final AmqpProtocolVersion defaultSupportedReply, + final long id, + final NetworkConnection network) { - this(appRegistry,fqdn,supported,id); + this(appRegistry, supported, defaultSupportedReply, id); setNetworkConnection(network); } - public MultiVersionProtocolEngine(IApplicationRegistry appRegistry, - String fqdn, - Set supported, - long id) + public MultiVersionProtocolEngine(final IApplicationRegistry appRegistry, + final Set supported, + final AmqpProtocolVersion defaultSupportedReply, + final long id) { + if(defaultSupportedReply != null && !supported.contains(defaultSupportedReply)) + { + throw new IllegalArgumentException("The configured default reply (" + defaultSupportedReply + + ") to an unsupported protocol version initiation is itself not supported!"); + } + _id = id; _appRegistry = appRegistry; - _fqdn = fqdn; _supported = supported; - + _defaultSupportedReply = defaultSupportedReply; } @@ -198,6 +205,15 @@ public class MultiVersionProtocolEngine implements ServerProtocolEngine public void setNetworkConnection(NetworkConnection network, Sender sender) { _network = network; + SocketAddress address = _network.getLocalAddress(); + if (address instanceof InetSocketAddress) + { + _fqdn = ((InetSocketAddress) address).getHostName(); + } + else + { + throw new IllegalArgumentException("Unsupported socket address class: " + address); + } _sender = sender; } @@ -445,14 +461,18 @@ public class MultiVersionProtocolEngine implements ServerProtocolEngine ServerProtocolEngine newDelegate = null; - byte[] newestSupported = null; + byte[] supportedReplyBytes = null; + byte[] defaultSupportedReplyBytes = null; + AmqpProtocolVersion supportedReplyVersion = null; + //Check the supported versions for a header match, and if there is one save the + //delegate. Also save most recent supported version and associated reply header bytes for(int i = 0; newDelegate == null && i < _creators.length; i++) { - if(_supported.contains(_creators[i].getVersion())) { - newestSupported = _creators[i].getHeaderIdentifier(); + supportedReplyBytes = _creators[i].getHeaderIdentifier(); + supportedReplyVersion = _creators[i].getVersion(); byte[] compareBytes = _creators[i].getHeaderIdentifier(); boolean equal = true; for(int j = 0; equal && j _supported; + private final AmqpProtocolVersion _defaultSupportedReply; - public MultiVersionProtocolEngineFactory(String fqdn, Set supportedVersions) + public MultiVersionProtocolEngineFactory(final Set supportedVersions, final AmqpProtocolVersion defaultSupportedReply) { + if(defaultSupportedReply != null && !supportedVersions.contains(defaultSupportedReply)) + { + throw new IllegalArgumentException("The configured default reply (" + defaultSupportedReply + + ") to an unsupported protocol version initiation is itself not supported!"); + } + _appRegistry = ApplicationRegistry.getInstance(); - _fqdn = fqdn; _supported = supportedVersions; - } - - public ServerProtocolEngine newProtocolEngine(NetworkConnection network) - { - return new MultiVersionProtocolEngine(_appRegistry, _fqdn, _supported, network, ID_GENERATOR.getAndIncrement()); + _defaultSupportedReply = defaultSupportedReply; } public ServerProtocolEngine newProtocolEngine() { - return new MultiVersionProtocolEngine(_appRegistry, _fqdn, _supported, ID_GENERATOR.getAndIncrement()); + return new MultiVersionProtocolEngine(_appRegistry, _supported, _defaultSupportedReply, ID_GENERATOR.getAndIncrement()); } } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/protocol/ProtocolEngine_0_10.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/protocol/ProtocolEngine_0_10.java index 5d4b8c603b..182ef1ed82 100755 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/protocol/ProtocolEngine_0_10.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/protocol/ProtocolEngine_0_10.java @@ -21,15 +21,19 @@ package org.apache.qpid.server.protocol; import org.apache.qpid.protocol.ServerProtocolEngine; +import org.apache.qpid.server.configuration.ConfigStore; +import org.apache.qpid.server.configuration.ConfiguredObject; +import org.apache.qpid.server.configuration.ConnectionConfig; +import org.apache.qpid.server.configuration.ConnectionConfigType; +import org.apache.qpid.server.configuration.VirtualHostConfig; +import org.apache.qpid.server.logging.messages.ConnectionMessages; +import org.apache.qpid.server.registry.IApplicationRegistry; +import org.apache.qpid.server.transport.ServerConnection; import org.apache.qpid.transport.Sender; -import org.apache.qpid.transport.network.InputHandler; import org.apache.qpid.transport.network.Assembler; import org.apache.qpid.transport.network.Disassembler; +import org.apache.qpid.transport.network.InputHandler; import org.apache.qpid.transport.network.NetworkConnection; -import org.apache.qpid.server.configuration.*; -import org.apache.qpid.server.transport.ServerConnection; -import org.apache.qpid.server.logging.messages.ConnectionMessages; -import org.apache.qpid.server.registry.IApplicationRegistry; import java.net.SocketAddress; import java.nio.ByteBuffer; @@ -86,8 +90,8 @@ public class ProtocolEngine_0_10 extends InputHandler implements ServerProtocol _connection.setSender(new Disassembler(sender, MAX_FRAME_SIZE)); // FIXME Two log messages to maintain compatibility with earlier protocol versions - _connection.getLogActor().message(ConnectionMessages.OPEN(null, null, false, false)); - _connection.getLogActor().message(ConnectionMessages.OPEN(null, "0-10", false, true)); + _connection.getLogActor().message(ConnectionMessages.OPEN(null, null, null, false, false, false)); + _connection.getLogActor().message(ConnectionMessages.OPEN(null, "0-10", null, false, true, false)); } public SocketAddress getRemoteAddress() diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/protocol/v1_0/SendingLink_1_0.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/protocol/v1_0/SendingLink_1_0.java index ed9d58994a..de2e1b69da 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/protocol/v1_0/SendingLink_1_0.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/protocol/v1_0/SendingLink_1_0.java @@ -29,7 +29,6 @@ import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import org.apache.qpid.AMQException; import org.apache.qpid.AMQInternalException; -import org.apache.qpid.AMQInvalidArgumentException; import org.apache.qpid.AMQSecurityException; import org.apache.qpid.amqp_1_0.transport.DeliveryStateHandler; import org.apache.qpid.amqp_1_0.transport.LinkEndpoint; @@ -54,6 +53,7 @@ import org.apache.qpid.amqp_1_0.type.transport.AmqpError; import org.apache.qpid.amqp_1_0.type.transport.Detach; import org.apache.qpid.amqp_1_0.type.transport.Error; import org.apache.qpid.amqp_1_0.type.transport.Transfer; +import org.apache.qpid.filter.selector.ParseException; import org.apache.qpid.server.exchange.DirectExchange; import org.apache.qpid.server.exchange.Exchange; import org.apache.qpid.server.exchange.TopicExchange; @@ -135,7 +135,7 @@ public class SendingLink_1_0 implements SendingLinkListener, Link_1_0, DeliveryS actualFilters.put(entry.getKey(), entry.getValue()); } - catch (AMQInvalidArgumentException e) + catch (ParseException e) { Error error = new Error(); error.setCondition(AmqpError.INVALID_FIELD); diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/AMQPriorityQueue.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/AMQPriorityQueue.java index 2c04a626ff..f6bf6626a0 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/AMQPriorityQueue.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/AMQPriorityQueue.java @@ -20,9 +20,10 @@ */ package org.apache.qpid.server.queue; -import java.util.Map; import org.apache.qpid.server.virtualhost.VirtualHost; +import java.util.Map; + public class AMQPriorityQueue extends OutOfOrderQueue { protected AMQPriorityQueue(final String name, @@ -39,6 +40,6 @@ public class AMQPriorityQueue extends OutOfOrderQueue public int getPriorities() { - return ((PriorityQueueList) _entries).getPriorities(); + return ((PriorityQueueList) getEntries()).getPriorities(); } } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueue.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueue.java index 32d9c4878a..e643338c3d 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueue.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueue.java @@ -22,20 +22,18 @@ package org.apache.qpid.server.queue; import org.apache.qpid.AMQException; import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.server.AMQChannel; -import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin; -import org.apache.qpid.server.logging.LogSubject; -import org.apache.qpid.server.protocol.AMQSessionModel; import org.apache.qpid.server.binding.Binding; import org.apache.qpid.server.configuration.QueueConfig; +import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin; import org.apache.qpid.server.exchange.Exchange; import org.apache.qpid.server.exchange.ExchangeReferrer; +import org.apache.qpid.server.logging.LogSubject; import org.apache.qpid.server.management.Managable; import org.apache.qpid.server.management.ManagedObject; +import org.apache.qpid.server.protocol.AMQSessionModel; import org.apache.qpid.server.security.AuthorizationHolder; import org.apache.qpid.server.store.TransactionLogResource; import org.apache.qpid.server.subscription.Subscription; -import org.apache.qpid.server.txn.ServerTransaction; import org.apache.qpid.server.virtualhost.VirtualHost; import java.util.List; @@ -142,10 +140,9 @@ public interface AMQQueue extends Managable, Comparable, ExchangeRefer public List getMessagesRangeOnTheQueue(final long fromPosition, final long toPosition); - void moveMessagesToAnotherQueue(long fromMessageId, long toMessageId, String queueName, - ServerTransaction transaction); + void moveMessagesToAnotherQueue(long fromMessageId, long toMessageId, String queueName); - void copyMessagesToAnotherQueue(long fromMessageId, long toMessageId, String queueName, ServerTransaction transaction); + void copyMessagesToAnotherQueue(long fromMessageId, long toMessageId, String queueName); void removeMessagesFromQueue(long fromMessageId, long toMessageId); diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueueFactory.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueueFactory.java index 14ca147982..e04ab8cfe9 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueueFactory.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueueFactory.java @@ -20,8 +20,6 @@ */ package org.apache.qpid.server.queue; -import java.util.HashMap; -import java.util.Map; import org.apache.qpid.AMQException; import org.apache.qpid.AMQSecurityException; import org.apache.qpid.exchange.ExchangeDefaults; @@ -35,6 +33,9 @@ import org.apache.qpid.server.exchange.ExchangeRegistry; import org.apache.qpid.server.registry.ApplicationRegistry; import org.apache.qpid.server.virtualhost.VirtualHost; +import java.util.HashMap; +import java.util.Map; + public class AMQQueueFactory { public static final String X_QPID_PRIORITIES = "x-qpid-priorities"; @@ -48,6 +49,10 @@ public class AMQQueueFactory public static final String X_QPID_MAXIMUM_DELIVERY_COUNT = "x-qpid-maximum-delivery-count"; public static final String DEFAULT_DLQ_NAME_SUFFIX = "_DLQ"; + private AMQQueueFactory() + { + } + private abstract static class QueueProperty { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueueMBean.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueueMBean.java index 143a6ae8ca..b0d4cb3486 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueueMBean.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueueMBean.java @@ -20,6 +20,7 @@ */ package org.apache.qpid.server.queue; +import org.apache.commons.lang.time.FastDateFormat; import org.apache.log4j.Logger; import org.apache.qpid.AMQException; @@ -31,12 +32,10 @@ import org.apache.qpid.management.common.mbeans.annotations.MBeanDescription; import org.apache.qpid.server.exchange.Exchange; import org.apache.qpid.server.management.AMQManagedObject; import org.apache.qpid.server.management.ManagedObject; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.message.AMQMessageHeader; import org.apache.qpid.server.message.AMQMessage; +import org.apache.qpid.server.message.AMQMessageHeader; import org.apache.qpid.server.message.MessageTransferMessage; -import org.apache.qpid.server.txn.ServerTransaction; -import org.apache.qpid.server.txn.LocalTransaction; +import org.apache.qpid.server.message.ServerMessage; import org.apache.qpid.transport.MessageProperties; import javax.management.JMException; @@ -56,9 +55,10 @@ import javax.management.openmbean.SimpleType; import javax.management.openmbean.TabularData; import javax.management.openmbean.TabularDataSupport; import javax.management.openmbean.TabularType; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; -import java.text.SimpleDateFormat; -import java.util.*; /** * AMQQueueMBean is the management bean for an {@link AMQQueue}. @@ -72,11 +72,13 @@ public class AMQQueueMBean extends AMQManagedObject implements ManagedQueue, Que { /** Used for debugging purposes. */ - private static final Logger _logger = Logger.getLogger(AMQQueueMBean.class); + private static final Logger LOGGER = Logger.getLogger(AMQQueueMBean.class); /** Date/time format used for message expiration and message timestamp formatting */ public static final String JMSTIMESTAMP_DATETIME_FORMAT = "MM-dd-yy HH:mm:ss.SSS z"; + private static final FastDateFormat FAST_DATE_FORMAT = FastDateFormat.getInstance(JMSTIMESTAMP_DATETIME_FORMAT); + private final AMQQueue _queue; private final String _queueName; // OpenMBean data types for viewMessages method @@ -347,14 +349,14 @@ public class AMQQueueMBean extends AMQManagedObject implements ManagedQueue, Que public void notifyClients(NotificationCheck notification, AMQQueue queue, String notificationMsg) { // important : add log to the log file - monitoring tools may be looking for this - _logger.info(notification.name() + " On Queue " + queue.getNameShortString() + " - " + notificationMsg); + LOGGER.info(notification.name() + " On Queue " + queue.getNameShortString() + " - " + notificationMsg); notificationMsg = notification.name() + " " + notificationMsg; _lastNotification = - new Notification(MonitorNotification.THRESHOLD_VALUE_EXCEEDED, this, ++_notificationSequenceNumber, + new Notification(MonitorNotification.THRESHOLD_VALUE_EXCEEDED, this, incrementAndGetSequenceNumber(), System.currentTimeMillis(), notificationMsg); - _broadcaster.sendNotification(_lastNotification); + getBroadcaster().sendNotification(_lastNotification); } public Notification getLastNotification() @@ -491,7 +493,7 @@ public class AMQQueueMBean extends AMQManagedObject implements ManagedQueue, Que ContentHeaderBody headerBody = msg.getContentHeaderBody(); // Create header attributes list headerAttributes = getMessageHeaderProperties(headerBody); - itemValues = new Object[]{msg.getMessageId(), headerAttributes, headerBody.bodySize, queueEntry.isRedelivered(), position, queueEntry.getDeliveryCount()}; + itemValues = new Object[]{msg.getMessageId(), headerAttributes, headerBody.getBodySize(), queueEntry.isRedelivered(), position, queueEntry.getDeliveryCount()}; } else if(serverMsg instanceof MessageTransferMessage) { @@ -589,18 +591,8 @@ public class AMQQueueMBean extends AMQManagedObject implements ManagedQueue, Que private void addStringifiedJMSTimestamoAndJMSExpiration(final List list, final long expirationDate, final long timestampDate) { - final SimpleDateFormat dateFormat; - if (expirationDate != 0 || timestampDate != 0) - { - dateFormat = new SimpleDateFormat(JMSTIMESTAMP_DATETIME_FORMAT); - } - else - { - dateFormat = null; - } - - final String formattedExpirationDate = (expirationDate != 0) ? dateFormat.format(new Date(expirationDate)) : null; - final String formattedTimestampDate = (timestampDate != 0) ? dateFormat.format(new Date(timestampDate)) : null; + final String formattedExpirationDate = (expirationDate != 0) ? FAST_DATE_FORMAT.format(expirationDate) : null; + final String formattedTimestampDate = (timestampDate != 0) ? FAST_DATE_FORMAT.format(timestampDate) : null; list.add("JMSExpiration = " + formattedExpirationDate); list.add("JMSTimestamp = " + formattedTimestampDate); } @@ -619,9 +611,7 @@ public class AMQQueueMBean extends AMQManagedObject implements ManagedQueue, Que throw new OperationsException("\"From MessageId\" should be greater than 0 and less than \"To MessageId\""); } - ServerTransaction txn = new LocalTransaction(_queue.getVirtualHost().getMessageStore()); - _queue.moveMessagesToAnotherQueue(fromMessageId, toMessageId, toQueueName, txn); - txn.commit(); + _queue.moveMessagesToAnotherQueue(fromMessageId, toMessageId, toQueueName); } /** @@ -654,13 +644,7 @@ public class AMQQueueMBean extends AMQManagedObject implements ManagedQueue, Que throw new OperationsException("\"From MessageId\" should be greater than 0 and less than \"To MessageId\""); } - ServerTransaction txn = new LocalTransaction(_queue.getVirtualHost().getMessageStore()); - - _queue.copyMessagesToAnotherQueue(fromMessageId, toMessageId, toQueueName, txn); - - txn.commit(); - - + _queue.copyMessagesToAnotherQueue(fromMessageId, toMessageId, toQueueName); } /** diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/BaseQueue.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/BaseQueue.java index 0bd40e8f13..35b7cac1a1 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/BaseQueue.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/BaseQueue.java @@ -21,10 +21,10 @@ package org.apache.qpid.server.queue; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.store.TransactionLogResource; import org.apache.qpid.AMQException; import org.apache.qpid.framing.AMQShortString; +import org.apache.qpid.server.message.ServerMessage; +import org.apache.qpid.server.store.TransactionLogResource; public interface BaseQueue extends TransactionLogResource { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/ConflationQueue.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/ConflationQueue.java index b5293f51be..2c645cc555 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/ConflationQueue.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/ConflationQueue.java @@ -41,7 +41,7 @@ public class ConflationQueue extends SimpleAMQQueue public String getConflationKey() { - return ((ConflationQueueList) _entries).getConflationKey(); + return ((ConflationQueueList) getEntries()).getConflationKey(); } } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/ConflationQueueList.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/ConflationQueueList.java index ab0a567114..6a2e4f155d 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/ConflationQueueList.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/ConflationQueueList.java @@ -21,13 +21,13 @@ package org.apache.qpid.server.queue; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicReference; - import org.apache.qpid.server.message.ServerMessage; import org.apache.qpid.server.txn.AutoCommitTransaction; import org.apache.qpid.server.txn.ServerTransaction; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicReference; + public class ConflationQueueList extends SimpleQueueEntryList { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/Filterable.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/Filterable.java index eaa3992e98..50d8f4166d 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/Filterable.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/Filterable.java @@ -20,8 +20,6 @@ */ package org.apache.qpid.server.queue; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.AMQException; import org.apache.qpid.server.message.AMQMessageHeader; public interface Filterable diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/InboundMessageAdapter.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/InboundMessageAdapter.java index 31e9725e47..bbc33ca846 100755 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/InboundMessageAdapter.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/InboundMessageAdapter.java @@ -21,9 +21,9 @@ package org.apache.qpid.server.queue; -import org.apache.qpid.server.message.InboundMessage; -import org.apache.qpid.server.message.AMQMessageHeader; import org.apache.qpid.framing.AMQShortString; +import org.apache.qpid.server.message.AMQMessageHeader; +import org.apache.qpid.server.message.InboundMessage; public class InboundMessageAdapter implements InboundMessage { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/IncomingMessage.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/IncomingMessage.java index 19a7a15ad1..c5a610c7b6 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/IncomingMessage.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/IncomingMessage.java @@ -20,25 +20,26 @@ */ package org.apache.qpid.server.queue; -import org.apache.qpid.framing.abstraction.MessagePublishInfo; -import org.apache.qpid.framing.abstraction.ContentChunk; -import org.apache.qpid.framing.ContentHeaderBody; +import org.apache.log4j.Logger; + +import org.apache.qpid.AMQException; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.framing.BasicContentHeaderProperties; -import org.apache.qpid.server.store.StoredMessage; -import org.apache.qpid.server.registry.ApplicationRegistry; +import org.apache.qpid.framing.ContentHeaderBody; +import org.apache.qpid.framing.abstraction.ContentChunk; +import org.apache.qpid.framing.abstraction.MessagePublishInfo; import org.apache.qpid.server.exchange.Exchange; -import org.apache.qpid.server.message.InboundMessage; import org.apache.qpid.server.message.AMQMessageHeader; import org.apache.qpid.server.message.EnqueableMessage; +import org.apache.qpid.server.message.InboundMessage; import org.apache.qpid.server.message.MessageContentSource; import org.apache.qpid.server.message.MessageMetaData; -import org.apache.qpid.AMQException; -import org.apache.log4j.Logger; +import org.apache.qpid.server.registry.ApplicationRegistry; +import org.apache.qpid.server.store.StoredMessage; +import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; -import java.nio.ByteBuffer; public class IncomingMessage implements Filterable, InboundMessage, EnqueableMessage, MessageContentSource { @@ -69,8 +70,6 @@ public class IncomingMessage implements Filterable, InboundMessage, EnqueableMes private Exchange _exchange; - - private int _receivedChunkCount = 0; private List _contentChunks = new ArrayList(); // we keep both the original meta data object and the store reference to it just in case the @@ -79,13 +78,20 @@ public class IncomingMessage implements Filterable, InboundMessage, EnqueableMes private MessageMetaData _messageMetaData; private StoredMessage _storedMessageHandle; + private Object _connectionReference; public IncomingMessage( final MessagePublishInfo info ) + { + this(info, null); + } + + public IncomingMessage(MessagePublishInfo info, Object reference) { _messagePublishInfo = info; + _connectionReference = reference; } public void setContentHeaderBody(final ContentHeaderBody contentHeaderBody) throws AMQException @@ -124,12 +130,6 @@ public class IncomingMessage implements Filterable, InboundMessage, EnqueableMes } - public MessageMetaData headersReceived() - { - - return headersReceived(System.currentTimeMillis()); - } - public MessageMetaData headersReceived(long currentTime) { _messageMetaData = new MessageMetaData(_messagePublishInfo, _contentHeaderBody, 0, currentTime); @@ -142,21 +142,15 @@ public class IncomingMessage implements Filterable, InboundMessage, EnqueableMes return _destinationQueues; } - public int addContentBodyFrame(final ContentChunk contentChunk) - throws AMQException + public void addContentBodyFrame(final ContentChunk contentChunk) throws AMQException { - _storedMessageHandle.addContent((int)_bodyLengthReceived, ByteBuffer.wrap(contentChunk.getData())); _bodyLengthReceived += contentChunk.getSize(); _contentChunks.add(contentChunk); - - - - return _receivedChunkCount++; } public boolean allContentReceived() { - return (_bodyLengthReceived == getContentHeader().bodySize); + return (_bodyLengthReceived == getContentHeader().getBodySize()); } public AMQShortString getExchange() @@ -217,7 +211,7 @@ public class IncomingMessage implements Filterable, InboundMessage, EnqueableMes public long getSize() { - return getContentHeader().bodySize; + return getContentHeader().getBodySize(); } public long getMessageNumber() @@ -251,18 +245,12 @@ public class IncomingMessage implements Filterable, InboundMessage, EnqueableMes return _expiration; } - public int getReceivedChunkCount() - { - return _receivedChunkCount; - } - - public int getBodyCount() throws AMQException { return _contentChunks.size(); } - public ContentChunk getContentChunk(int index) throws IllegalArgumentException, AMQException + public ContentChunk getContentChunk(int index) { return _contentChunks.get(index); } @@ -317,4 +305,14 @@ public class IncomingMessage implements Filterable, InboundMessage, EnqueableMes { return _storedMessageHandle; } + + public Object getConnectionReference() + { + return _connectionReference; + } + + public MessageMetaData getMessageMetaData() + { + return _messageMetaData; + } } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/NotificationCheck.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/NotificationCheck.java index d1fb0f3fe6..c1ebbe412f 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/NotificationCheck.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/NotificationCheck.java @@ -20,7 +20,6 @@ */ package org.apache.qpid.server.queue; -import org.apache.qpid.AMQException; import org.apache.qpid.server.message.ServerMessage; public enum NotificationCheck diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/OutOfOrderQueue.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/OutOfOrderQueue.java index 0220a553a7..53121fc031 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/OutOfOrderQueue.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/OutOfOrderQueue.java @@ -1,11 +1,11 @@ package org.apache.qpid.server.queue; -import java.util.Map; - import org.apache.qpid.server.subscription.Subscription; import org.apache.qpid.server.subscription.SubscriptionList; import org.apache.qpid.server.virtualhost.VirtualHost; +import java.util.Map; + public abstract class OutOfOrderQueue extends SimpleAMQQueue { @@ -20,7 +20,7 @@ public abstract class OutOfOrderQueue extends SimpleAMQQueue protected void checkSubscriptionsNotAheadOfDelivery(final QueueEntry entry) { // check that all subscriptions are not in advance of the entry - SubscriptionList.SubscriptionNodeIterator subIter = _subscriptionList.iterator(); + SubscriptionList.SubscriptionNodeIterator subIter = getSubscriptionList().iterator(); while(subIter.advance() && !entry.isAcquired()) { final Subscription subscription = subIter.getNode().getSubscription(); @@ -29,7 +29,7 @@ public abstract class OutOfOrderQueue extends SimpleAMQQueue QueueContext context = (QueueContext) subscription.getQueueContext(); if(context != null) { - QueueEntry released = context._releasedEntry; + QueueEntry released = context.getReleasedEntry(); while(!entry.isAcquired() && (released == null || released.compareTo(entry) > 0)) { if(QueueContext._releasedUpdater.compareAndSet(context,released,entry)) @@ -38,7 +38,7 @@ public abstract class OutOfOrderQueue extends SimpleAMQQueue } else { - released = context._releasedEntry; + released = context.getReleasedEntry(); } } } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/PriorityQueueList.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/PriorityQueueList.java index 79d3ab5bd0..05141a48a1 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/PriorityQueueList.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/PriorityQueueList.java @@ -74,7 +74,7 @@ public class PriorityQueueList implements QueueEntryList { final QueueEntryList nodeEntryList = node.getQueueEntryList(); int index; - for(index = _priorityLists.length-1; _priorityLists[index] != nodeEntryList; index--); + for(index = _priorityLists.length-1; _priorityLists[index] != nodeEntryList; index--) {}; while(next == null && index != 0) { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/QueueContext.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/QueueContext.java index 825a85a89c..c8f04c7b96 100755 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/QueueContext.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/QueueContext.java @@ -25,8 +25,8 @@ import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; final class QueueContext implements AMQQueue.Context { - volatile QueueEntry _lastSeenEntry; - volatile QueueEntry _releasedEntry; + private volatile QueueEntry _lastSeenEntry; + private volatile QueueEntry _releasedEntry; static final AtomicReferenceFieldUpdater _lastSeenUpdater = @@ -46,4 +46,10 @@ final class QueueContext implements AMQQueue.Context { return _lastSeenEntry; } + + + QueueEntry getReleasedEntry() + { + return _releasedEntry; + } } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/QueueEntry.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/QueueEntry.java index 142cfddb39..c33309b6d3 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/QueueEntry.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/QueueEntry.java @@ -1,10 +1,8 @@ package org.apache.qpid.server.queue; -import java.util.Collection; - import org.apache.qpid.AMQException; -import org.apache.qpid.server.subscription.Subscription; import org.apache.qpid.server.message.ServerMessage; +import org.apache.qpid.server.subscription.Subscription; /* * diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/QueueEntryImpl.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/QueueEntryImpl.java index 82c6a2f127..404907183a 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/QueueEntryImpl.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/QueueEntryImpl.java @@ -34,7 +34,6 @@ import org.apache.qpid.server.message.AMQMessageHeader; import org.apache.qpid.server.message.MessageReference; import org.apache.qpid.server.message.ServerMessage; import org.apache.qpid.server.subscription.Subscription; -import org.apache.qpid.server.txn.AutoCommitTransaction; import org.apache.qpid.server.txn.LocalTransaction; import org.apache.qpid.server.txn.ServerTransaction; @@ -416,11 +415,19 @@ public abstract class QueueEntryImpl implements QueueEntry if (alternateExchange != null) { - final List rerouteQueues = alternateExchange.route(new InboundMessageAdapter(this)); + InboundMessageAdapter inboundMessageAdapter = new InboundMessageAdapter(this); + List queues = alternateExchange.route(inboundMessageAdapter); final ServerMessage message = getMessage(); - if (rerouteQueues != null && rerouteQueues.size() != 0) + if ((queues == null || queues.size() == 0) && alternateExchange.getAlternateExchange() != null) { + queues = alternateExchange.getAlternateExchange().route(inboundMessageAdapter); + } + + + if (queues != null && queues.size() != 0) + { + final List rerouteQueues = queues; ServerTransaction txn = new LocalTransaction(getQueue().getVirtualHost().getMessageStore()); txn.enqueue(rerouteQueues, message, new ServerTransaction.Action() diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/QueueRegistry.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/QueueRegistry.java index a537e0c83f..80f6bd1493 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/QueueRegistry.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/QueueRegistry.java @@ -20,7 +20,6 @@ */ package org.apache.qpid.server.queue; -import org.apache.qpid.AMQException; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.server.virtualhost.VirtualHost; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/QueueRunner.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/QueueRunner.java index 0d44fe7cf3..22a2029494 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/QueueRunner.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/QueueRunner.java @@ -20,17 +20,16 @@ */ package org.apache.qpid.server.queue; -import org.apache.log4j.Logger; -import org.apache.qpid.AMQException; -import org.apache.qpid.server.logging.actors.CurrentActor; -import org.apache.qpid.server.queue.QueueRunner; -import org.apache.qpid.server.queue.SimpleAMQQueue; - import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; +import org.apache.log4j.Logger; +import org.apache.qpid.AMQException; +import org.apache.qpid.server.logging.actors.CurrentActor; +import org.apache.qpid.transport.TransportException; + /** * QueueRunners are Runnables used to process a queue when requiring * asynchronous message delivery to subscriptions, which is necessary @@ -47,7 +46,6 @@ public class QueueRunner implements Runnable private static int SCHEDULED = 1; private static int RUNNING = 2; - private final AtomicInteger _scheduled = new AtomicInteger(IDLE); private final AtomicBoolean _stateChange = new AtomicBoolean(); @@ -55,8 +53,6 @@ public class QueueRunner implements Runnable private final AtomicLong _lastRunAgain = new AtomicLong(); private final AtomicLong _lastRunTime = new AtomicLong(); - private long _continues; - public QueueRunner(SimpleAMQQueue queue) { _queue = queue; @@ -74,24 +70,35 @@ public class QueueRunner implements Runnable runAgain = _queue.processQueue(this); } - catch (AMQException e) + catch (final AMQException e) { _logger.error("Exception during asynchronous delivery by " + toString(), e); } - finally + catch (final TransportException transe) { - CurrentActor.remove(); + final String errorMessage = "Problem during asynchronous delivery by " + toString(); + if(_logger.isDebugEnabled()) + { + _logger.debug(errorMessage, transe); + } + else + { + _logger.info(errorMessage + ' ' + transe.getMessage()); + } } - _scheduled.compareAndSet(RUNNING, IDLE); - long stateChangeCount = _queue.getStateChangeCount(); - _lastRunAgain.set(runAgain); - _lastRunTime.set(System.nanoTime()); - if(runAgain == 0L || runAgain != stateChangeCount || _stateChange.compareAndSet(true,false)) + finally { - _continues++; - if(_scheduled.compareAndSet(IDLE, SCHEDULED)) + CurrentActor.remove(); + _scheduled.compareAndSet(RUNNING, IDLE); + final long stateChangeCount = _queue.getStateChangeCount(); + _lastRunAgain.set(runAgain); + _lastRunTime.set(System.nanoTime()); + if(runAgain == 0L || runAgain != stateChangeCount || _stateChange.compareAndSet(true,false)) { - _queue.execute(this); + if(_scheduled.compareAndSet(IDLE, SCHEDULED)) + { + _queue.execute(this); + } } } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/SimpleAMQQueue.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/SimpleAMQQueue.java index dfad9157c5..c37d0e2202 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/SimpleAMQQueue.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/SimpleAMQQueue.java @@ -27,12 +27,16 @@ import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import javax.management.JMException; + +import javax.management.JMException; + import org.apache.log4j.Logger; import org.apache.qpid.AMQException; import org.apache.qpid.AMQSecurityException; @@ -99,13 +103,10 @@ public class SimpleAMQQueue implements AMQQueue, Subscription.StateListener, Mes private Exchange _alternateExchange; - /** Used to track bindings to exchanges so that on deletion they can easily be cancelled. */ + private final QueueEntryList _entries; - - protected final QueueEntryList _entries; - - protected final SubscriptionList _subscriptionList = new SubscriptionList(); + private final SubscriptionList _subscriptionList = new SubscriptionList(); private volatile Subscription _exclusiveSubscriber; @@ -137,19 +138,19 @@ public class SimpleAMQQueue implements AMQQueue, Subscription.StateListener, Mes private final AtomicInteger _bindingCountHigh = new AtomicInteger(); /** max allowed size(KB) of a single message */ - public long _maximumMessageSize = ApplicationRegistry.getInstance().getConfiguration().getMaximumMessageSize(); + private long _maximumMessageSize = ApplicationRegistry.getInstance().getConfiguration().getMaximumMessageSize(); /** max allowed number of messages on a queue. */ - public long _maximumMessageCount = ApplicationRegistry.getInstance().getConfiguration().getMaximumMessageCount(); + private long _maximumMessageCount = ApplicationRegistry.getInstance().getConfiguration().getMaximumMessageCount(); /** max queue depth for the queue */ - public long _maximumQueueDepth = ApplicationRegistry.getInstance().getConfiguration().getMaximumQueueDepth(); + private long _maximumQueueDepth = ApplicationRegistry.getInstance().getConfiguration().getMaximumQueueDepth(); /** maximum message age before alerts occur */ - public long _maximumMessageAge = ApplicationRegistry.getInstance().getConfiguration().getMaximumMessageAge(); + private long _maximumMessageAge = ApplicationRegistry.getInstance().getConfiguration().getMaximumMessageAge(); /** the minimum interval between sending out consecutive alerts of the same type */ - public long _minimumAlertRepeatGap = ApplicationRegistry.getInstance().getConfiguration().getMinimumAlertRepeatGap(); + private long _minimumAlertRepeatGap = ApplicationRegistry.getInstance().getConfiguration().getMinimumAlertRepeatGap(); private long _capacity = ApplicationRegistry.getInstance().getConfiguration().getCapacity(); @@ -167,7 +168,7 @@ public class SimpleAMQQueue implements AMQQueue, Subscription.StateListener, Mes private AtomicInteger _deliveredMessages = new AtomicInteger(); private AtomicBoolean _stopped = new AtomicBoolean(false); - private final ConcurrentMap _blockedChannels = new ConcurrentHashMap(); + private final Set _blockedChannels = new ConcurrentSkipListSet(); private final AtomicBoolean _deleted = new AtomicBoolean(false); private final List _deleteTaskList = new CopyOnWriteArrayList(); @@ -455,7 +456,10 @@ public class SimpleAMQQueue implements AMQQueue, Subscription.StateListener, Mes } } - _activeSubscriberCount.incrementAndGet(); + if(subscription.isActive()) + { + _activeSubscriberCount.incrementAndGet(); + } subscription.setStateListener(this); subscription.setQueueContext(new QueueContext(_entries.getHead())); @@ -778,7 +782,9 @@ public class SimpleAMQQueue implements AMQQueue, Subscription.StateListener, Mes private boolean mightAssign(final Subscription sub, final QueueEntry entry) { if(_messageGroupManager == null || !sub.acquires()) + { return true; + } Subscription assigned = _messageGroupManager.getAssignedSubscription(entry); return (assigned == null) || (assigned == sub); } @@ -848,7 +854,7 @@ public class SimpleAMQQueue implements AMQQueue, Subscription.StateListener, Mes QueueContext context = (QueueContext) subscription.getQueueContext(); if(context != null) { - QueueEntry subnode = context._lastSeenEntry; + QueueEntry subnode = context.getLastSeenEntry(); if(subnode.compareTo(entry)<0) { return false; @@ -872,7 +878,7 @@ public class SimpleAMQQueue implements AMQQueue, Subscription.StateListener, Mes private void setLastSeenEntry(final Subscription sub, final QueueEntry entry) { QueueContext subContext = (QueueContext) sub.getQueueContext(); - QueueEntry releasedEntry = subContext._releasedEntry; + QueueEntry releasedEntry = subContext.getReleasedEntry(); QueueContext._lastSeenUpdater.set(subContext, entry); if(releasedEntry == entry) @@ -889,7 +895,7 @@ public class SimpleAMQQueue implements AMQQueue, Subscription.StateListener, Mes { QueueEntry oldEntry; - while((oldEntry = subContext._releasedEntry) == null || oldEntry.compareTo(entry) > 0) + while((oldEntry = subContext.getReleasedEntry()) == null || oldEntry.compareTo(entry) > 0) { if(QueueContext._releasedUpdater.compareAndSet(subContext, oldEntry, entry)) { @@ -1113,6 +1119,17 @@ public class SimpleAMQQueue implements AMQQueue, Subscription.StateListener, Mes return _stateChangeCount.get(); } + /** Used to track bindings to exchanges so that on deletion they can easily be cancelled. */ + protected QueueEntryList getEntries() + { + return _entries; + } + + protected SubscriptionList getSubscriptionList() + { + return _subscriptionList; + } + public static interface QueueEntryFilter { @@ -1226,19 +1243,10 @@ public class SimpleAMQQueue implements AMQQueue, Subscription.StateListener, Mes public void moveMessagesToAnotherQueue(final long fromMessageId, final long toMessageId, - String queueName, - ServerTransaction txn) throws IllegalArgumentException + String destinationQueueName) throws IllegalArgumentException { - final AMQQueue toQueue = getVirtualHost().getQueueRegistry().getQueue(new AMQShortString(queueName)); - if (toQueue == null) - { - throw new IllegalArgumentException("Queue '" + queueName + "' is not registered with the virtualhost."); - } - else if (toQueue == this) - { - throw new IllegalArgumentException("The destination queue cant be the same as the source queue"); - } + final AMQQueue toQueue = getValidatedDestinationQueue(destinationQueueName); List entries = getMessagesOnTheQueue(new QueueEntryFilter() { @@ -1258,65 +1266,68 @@ public class SimpleAMQQueue implements AMQQueue, Subscription.StateListener, Mes }); - - // Move the messages in on the message store. - for (final QueueEntry entry : entries) + final ServerTransaction txn = new LocalTransaction(getVirtualHost().getMessageStore()); + boolean shouldRollback = true; + try { - final ServerMessage message = entry.getMessage(); - txn.enqueue(toQueue, message, - new ServerTransaction.Action() - { - - public void postCommit() + // Move the messages in on the message store. + for (final QueueEntry entry : entries) + { + final ServerMessage message = entry.getMessage(); + txn.enqueue(toQueue, message, + new ServerTransaction.Action() { - try + + public void postCommit() { - toQueue.enqueue(message); + try + { + toQueue.enqueue(message); + } + catch (AMQException e) + { + throw new RuntimeException(e); + } } - catch (AMQException e) + + public void onRollback() { - throw new RuntimeException(e); + entry.release(); } - } - - public void onRollback() + }); + txn.dequeue(this, message, + new ServerTransaction.Action() { - entry.release(); - } - }); - txn.dequeue(this, message, - new ServerTransaction.Action() - { - public void postCommit() - { - entry.discard(); - } - - public void onRollback() - { + public void postCommit() + { + entry.discard(); + } - } - }); + public void onRollback() + { + } + }); + } + txn.commit(); + shouldRollback = false; + } + finally + { + if (shouldRollback) + { + txn.rollback(); + } } } public void copyMessagesToAnotherQueue(final long fromMessageId, final long toMessageId, - String queueName, - final ServerTransaction txn) throws IllegalArgumentException + String destinationQueueName) throws IllegalArgumentException { - final AMQQueue toQueue = getVirtualHost().getQueueRegistry().getQueue(new AMQShortString(queueName)); - if (toQueue == null) - { - throw new IllegalArgumentException("Queue '" + queueName + "' is not registered with the virtualhost."); - } - else if (toQueue == this) - { - throw new IllegalArgumentException("The destination queue cant be the same as the source queue"); - } + final AMQQueue toQueue = getValidatedDestinationQueue(destinationQueueName); List entries = getMessagesOnTheQueue(new QueueEntryFilter() { @@ -1334,36 +1345,63 @@ public class SimpleAMQQueue implements AMQQueue, Subscription.StateListener, Mes } }); - - // Move the messages in on the message store. - for (QueueEntry entry : entries) + final ServerTransaction txn = new LocalTransaction(_virtualHost.getMessageStore()); + boolean shouldRollback = true; + try { - final ServerMessage message = entry.getMessage(); - - txn.enqueue(toQueue, message, new ServerTransaction.Action() + // Copy the messages in on the message store. + for (QueueEntry entry : entries) { - public void postCommit() + final ServerMessage message = entry.getMessage(); + + txn.enqueue(toQueue, message, new ServerTransaction.Action() { - try + public void postCommit() { - toQueue.enqueue(message); + try + { + toQueue.enqueue(message); + } + catch (AMQException e) + { + throw new RuntimeException(e); + } } - catch (AMQException e) + + public void onRollback() { - throw new RuntimeException(e); } - } - - public void onRollback() - { + }); - } - }); + } + txn.commit(); + shouldRollback = false; + } + finally + { + if (shouldRollback) + { + txn.rollback(); + } } } + private AMQQueue getValidatedDestinationQueue(String queueName) + { + final AMQQueue toQueue = getVirtualHost().getQueueRegistry().getQueue(new AMQShortString(queueName)); + if (toQueue == null) + { + throw new IllegalArgumentException("Queue '" + queueName + "' is not registered with the virtualhost."); + } + else if (toQueue == this) + { + throw new IllegalArgumentException("The destination queue can't be the same as the source queue"); + } + return toQueue; + } + public void removeMessagesFromQueue(long fromMessageId, long toMessageId) { @@ -1543,10 +1581,16 @@ public class SimpleAMQQueue implements AMQQueue, Subscription.StateListener, Mes for(final QueueEntry entry : entries) { adapter.setEntry(entry); - final List rerouteQueues = _alternateExchange.route(adapter); + List queues = _alternateExchange.route(adapter); + if((queues == null || queues.size() == 0) && _alternateExchange.getAlternateExchange() != null) + { + queues = _alternateExchange.getAlternateExchange().route(adapter); + } + final ServerMessage message = entry.getMessage(); - if(rerouteQueues != null && rerouteQueues.size() != 0) + if(queues != null && queues.size() != 0) { + final List rerouteQueues = queues; txn.enqueue(rerouteQueues, entry.getMessage(), new ServerTransaction.Action() { @@ -1659,7 +1703,7 @@ public class SimpleAMQQueue implements AMQQueue, Subscription.StateListener, Mes //Overfull log message _logActor.message(_logSubject, QueueMessages.OVERFULL(_atomicQueueSize.get(), _capacity)); - _blockedChannels.putIfAbsent(channel, Boolean.TRUE); + _blockedChannels.add(channel); channel.block(this); @@ -1692,11 +1736,10 @@ public class SimpleAMQQueue implements AMQQueue, Subscription.StateListener, Mes _logActor.message(_logSubject, QueueMessages.UNDERFULL(_atomicQueueSize.get(), _flowResumeCapacity)); } - - for(AMQSessionModel c : _blockedChannels.keySet()) + for(final AMQSessionModel blockedChannel : _blockedChannels) { - c.unblock(this); - _blockedChannels.remove(c); + blockedChannel.unblock(this); + _blockedChannels.remove(blockedChannel); } } } @@ -1714,7 +1757,6 @@ public class SimpleAMQQueue implements AMQQueue, Subscription.StateListener, Mes public void deliverAsync(Subscription sub) { - //_stateChangeCount.incrementAndGet(); if(_exclusiveSubscriber == null) { deliverAsync(); @@ -1890,8 +1932,8 @@ public class SimpleAMQQueue implements AMQQueue, Subscription.StateListener, Mes QueueContext context = (QueueContext) sub.getQueueContext(); if(context != null) { - QueueEntry lastSeen = context._lastSeenEntry; - QueueEntry releasedNode = context._releasedEntry; + QueueEntry lastSeen = context.getLastSeenEntry(); + QueueEntry releasedNode = context.getReleasedEntry(); QueueEntry node = (releasedNode != null && lastSeen.compareTo(releasedNode)>=0) ? releasedNode : _entries.next(lastSeen); @@ -1913,8 +1955,8 @@ public class SimpleAMQQueue implements AMQQueue, Subscription.StateListener, Mes QueueContext._releasedUpdater.compareAndSet(context, releasedNode, null); } - lastSeen = context._lastSeenEntry; - releasedNode = context._releasedEntry; + lastSeen = context.getLastSeenEntry(); + releasedNode = context.getReleasedEntry(); node = (releasedNode != null && lastSeen.compareTo(releasedNode)>0) ? releasedNode : _entries.next(lastSeen); } return node; @@ -1930,8 +1972,8 @@ public class SimpleAMQQueue implements AMQQueue, Subscription.StateListener, Mes QueueContext context = (QueueContext) sub.getQueueContext(); if(context != null) { - QueueEntry releasedNode = context._releasedEntry; - return releasedNode == null || releasedNode.compareTo(entry) < 0; + QueueEntry releasedNode = context.getReleasedEntry(); + return releasedNode != null && releasedNode.compareTo(entry) < 0; } else { @@ -2255,8 +2297,7 @@ public class SimpleAMQQueue implements AMQQueue, Subscription.StateListener, Mes public boolean equals(Object o) { - return o != null - && o instanceof SimpleAMQQueue.QueueEntryListener + return o instanceof SimpleAMQQueue.QueueEntryListener && _sub == ((QueueEntryListener) o)._sub; } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/SimpleQueueEntryImpl.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/SimpleQueueEntryImpl.java index 0707dc045c..4a10d31d37 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/SimpleQueueEntryImpl.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/SimpleQueueEntryImpl.java @@ -22,9 +22,16 @@ package org.apache.qpid.server.queue; import org.apache.qpid.server.message.ServerMessage; +import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; + public class SimpleQueueEntryImpl extends QueueEntryImpl { - volatile SimpleQueueEntryImpl _next; + static final AtomicReferenceFieldUpdater + _nextUpdater = + AtomicReferenceFieldUpdater.newUpdater + (SimpleQueueEntryImpl.class, SimpleQueueEntryImpl.class, "_next"); + + private volatile SimpleQueueEntryImpl _next; public SimpleQueueEntryImpl(SimpleQueueEntryList queueEntryList) { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/SimpleQueueEntryList.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/SimpleQueueEntryList.java index b40e5a28c2..c82d1b984a 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/SimpleQueueEntryList.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/SimpleQueueEntryList.java @@ -20,9 +20,11 @@ */ package org.apache.qpid.server.queue; +import org.apache.qpid.server.message.ServerMessage; + import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; -import org.apache.qpid.server.message.ServerMessage; public class SimpleQueueEntryList implements QueueEntryList { @@ -40,12 +42,11 @@ public class SimpleQueueEntryList implements QueueEntryList - _nextUpdater = - AtomicReferenceFieldUpdater.newUpdater - (SimpleQueueEntryImpl.class, SimpleQueueEntryImpl.class, "_next"); + _nextUpdater = SimpleQueueEntryImpl._nextUpdater; private AtomicLong _scavenges = new AtomicLong(0L); private final long _scavengeCount = Integer.getInteger("qpid.queue.scavenge_count", 50); + private final AtomicReference _unscavengedHWM = new AtomicReference(); public SimpleQueueEntryList(AMQQueue queue) @@ -55,28 +56,17 @@ public class SimpleQueueEntryList implements QueueEntryList _scavengeCount) - { - _scavenges.set(0L); - scavenge(); - } - } - } - void scavenge() { + SimpleQueueEntryImpl hwm = _unscavengedHWM.getAndSet(null); SimpleQueueEntryImpl next = _head.getNextValidEntry(); - while (next != null) + if(hwm != null) { - next = next.getNextValidEntry(); + while (next != null && hwm.compareTo(next)>0) + { + next = next.getNextValidEntry(); + } } } @@ -126,7 +116,6 @@ public class SimpleQueueEntryList implements QueueEntryList { - private SimpleQueueEntryImpl _lastNode; QueueEntryIteratorImpl(SimpleQueueEntryImpl startNode) @@ -134,10 +123,9 @@ public class SimpleQueueEntryList implements QueueEntryList _scavengeCount) + { + _scavenges.set(0L); + scavenge(); + } + } + else + { + SimpleQueueEntryImpl unscavengedHWM = _unscavengedHWM.get(); + if(unscavengedHWM != null && (next == null || unscavengedHWM.compareTo(next) < 0)) + { + _unscavengedHWM.compareAndSet(unscavengedHWM, null); + } + } } public int getPriorities() diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/SortedQueue.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/SortedQueue.java index 865b3d1f48..446f57b142 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/SortedQueue.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/SortedQueue.java @@ -19,11 +19,12 @@ */ package org.apache.qpid.server.queue; -import java.util.Map; import org.apache.qpid.AMQException; import org.apache.qpid.server.message.ServerMessage; import org.apache.qpid.server.virtualhost.VirtualHost; +import java.util.Map; + public class SortedQueue extends OutOfOrderQueue { //Lock object to synchronize enqueue. Used instead of the object diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/SortedQueueEntryList.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/SortedQueueEntryList.java index 414a123c43..7f742d455d 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/SortedQueueEntryList.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/queue/SortedQueueEntryList.java @@ -21,12 +21,7 @@ package org.apache.qpid.server.queue; import org.apache.qpid.server.message.ServerMessage; - -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.BasicContentHeaderProperties; import org.apache.qpid.server.queue.SortedQueueEntryImpl.Colour; -import org.apache.qpid.server.store.StoreContext; /** * A sorted implementation of QueueEntryList. @@ -367,7 +362,7 @@ public class SortedQueueEntryList implements QueueEntryList _instance = new AtomicReference(null); - protected final ServerConfiguration _configuration; + private final ServerConfiguration _configuration; - protected final Map _acceptors = new HashMap(); + private final Map _acceptors = new HashMap(); - protected ManagedObjectRegistry _managedObjectRegistry; + private ManagedObjectRegistry _managedObjectRegistry; - protected AuthenticationManager _authenticationManager; + private AuthenticationManager _authenticationManager; - protected VirtualHostRegistry _virtualHostRegistry; + private VirtualHostRegistry _virtualHostRegistry; - protected SecurityManager _securityManager; + private SecurityManager _securityManager; - protected PluginManager _pluginManager; + private PluginManager _pluginManager; - protected ConfigurationManager _configurationManager; + private ConfigurationManager _configurationManager; - protected RootMessageLogger _rootMessageLogger; + private RootMessageLogger _rootMessageLogger; - protected CompositeStartupMessageLogger _startupMessageLogger; + private CompositeStartupMessageLogger _startupMessageLogger; - protected UUID _brokerId = UUID.randomUUID(); + private UUID _brokerId = UUID.randomUUID(); - protected QMFService _qmfService; + private QMFService _qmfService; private BrokerConfig _broker; @@ -114,17 +116,74 @@ public abstract class ApplicationRegistry implements IApplicationRegistry private BundleContext _bundleContext; - static + protected static Logger get_logger() { - Runtime.getRuntime().addShutdownHook(new Thread(new ShutdownService())); + return _logger; } - private static class ShutdownService implements Runnable + protected Map getAcceptors() { - public void run() - { - remove(); - } + return _acceptors; + } + + protected void setManagedObjectRegistry(ManagedObjectRegistry managedObjectRegistry) + { + _managedObjectRegistry = managedObjectRegistry; + } + + protected void setAuthenticationManager(AuthenticationManager authenticationManager) + { + _authenticationManager = authenticationManager; + } + + protected void setVirtualHostRegistry(VirtualHostRegistry virtualHostRegistry) + { + _virtualHostRegistry = virtualHostRegistry; + } + + protected void setSecurityManager(SecurityManager securityManager) + { + _securityManager = securityManager; + } + + protected void setPluginManager(PluginManager pluginManager) + { + _pluginManager = pluginManager; + } + + protected void setConfigurationManager(ConfigurationManager configurationManager) + { + _configurationManager = configurationManager; + } + + protected void setRootMessageLogger(RootMessageLogger rootMessageLogger) + { + _rootMessageLogger = rootMessageLogger; + } + + protected CompositeStartupMessageLogger getStartupMessageLogger() + { + return _startupMessageLogger; + } + + protected void setStartupMessageLogger(CompositeStartupMessageLogger startupMessageLogger) + { + _startupMessageLogger = startupMessageLogger; + } + + protected void setBrokerId(UUID brokerId) + { + _brokerId = brokerId; + } + + protected QMFService getQmfService() + { + return _qmfService; + } + + protected void setQmfService(QMFService qmfService) + { + _qmfService = qmfService; } public static void initialise(IApplicationRegistry instance) throws Exception @@ -201,7 +260,6 @@ public abstract class ApplicationRegistry implements IApplicationRegistry _logger.info("Shutting down ApplicationRegistry(" + instance + ")"); } instance.close(); - instance.getBroker().getSystem().removeBroker(instance.getBroker()); } } catch (Exception e) @@ -256,7 +314,7 @@ public abstract class ApplicationRegistry implements IApplicationRegistry _qmfService = new QMFService(getConfigStore(), this); - CurrentActor.get().message(BrokerMessages.STARTUP(QpidProperties.getReleaseVersion(), QpidProperties.getBuildVersion())); + logStartupMessages(CurrentActor.get()); _virtualHostRegistry = new VirtualHostRegistry(this); @@ -285,6 +343,7 @@ public abstract class ApplicationRegistry implements IApplicationRegistry } } + /** * Iterates across all discovered authentication manager factories, offering the security configuration to each. * Expects exactly one authentication manager to configure and initialise itself. @@ -358,57 +417,71 @@ public abstract class ApplicationRegistry implements IApplicationRegistry { _reportingTimer = new Timer("Statistics-Reporting", true); - class StatisticsReportingTask extends TimerTask + + + _reportingTimer.scheduleAtFixedRate(new StatisticsReportingTask(broker, virtualhost, reset), + report / 2, + report); + } + } + + private class StatisticsReportingTask extends TimerTask + { + private final int DELIVERED = 0; + private final int RECEIVED = 1; + + private boolean _broker; + private boolean _virtualhost; + private boolean _reset; + + + public StatisticsReportingTask(boolean broker, boolean virtualhost, boolean reset) + { + _broker = broker; + _virtualhost = virtualhost; + _reset = reset; + } + + public void run() + { + CurrentActor.set(new AbstractActor(ApplicationRegistry.getInstance().getRootMessageLogger()) { + public String getLogMessage() + { + return "[" + Thread.currentThread().getName() + "] "; + } + }); + + if (_broker) { - private final int DELIVERED = 0; - private final int RECEIVED = 1; - - public void run() + CurrentActor.get().message(BrokerMessages.STATS_DATA(DELIVERED, _dataDelivered.getPeak() / 1024.0, _dataDelivered.getTotal())); + CurrentActor.get().message(BrokerMessages.STATS_MSGS(DELIVERED, _messagesDelivered.getPeak(), _messagesDelivered.getTotal())); + CurrentActor.get().message(BrokerMessages.STATS_DATA(RECEIVED, _dataReceived.getPeak() / 1024.0, _dataReceived.getTotal())); + CurrentActor.get().message(BrokerMessages.STATS_MSGS(RECEIVED, _messagesReceived.getPeak(), _messagesReceived.getTotal())); + } + + if (_virtualhost) + { + for (VirtualHost vhost : getVirtualHostRegistry().getVirtualHosts()) { - CurrentActor.set(new AbstractActor(ApplicationRegistry.getInstance().getRootMessageLogger()) { - public String getLogMessage() - { - return "[" + Thread.currentThread().getName() + "] "; - } - }); - - if (broker) - { - CurrentActor.get().message(BrokerMessages.STATS_DATA(DELIVERED, _dataDelivered.getPeak() / 1024.0, _dataDelivered.getTotal())); - CurrentActor.get().message(BrokerMessages.STATS_MSGS(DELIVERED, _messagesDelivered.getPeak(), _messagesDelivered.getTotal())); - CurrentActor.get().message(BrokerMessages.STATS_DATA(RECEIVED, _dataReceived.getPeak() / 1024.0, _dataReceived.getTotal())); - CurrentActor.get().message(BrokerMessages.STATS_MSGS(RECEIVED, _messagesReceived.getPeak(), _messagesReceived.getTotal())); - } - - if (virtualhost) - { - for (VirtualHost vhost : getVirtualHostRegistry().getVirtualHosts()) - { - String name = vhost.getName(); - StatisticsCounter dataDelivered = vhost.getDataDeliveryStatistics(); - StatisticsCounter messagesDelivered = vhost.getMessageDeliveryStatistics(); - StatisticsCounter dataReceived = vhost.getDataReceiptStatistics(); - StatisticsCounter messagesReceived = vhost.getMessageReceiptStatistics(); - - CurrentActor.get().message(VirtualHostMessages.STATS_DATA(name, DELIVERED, dataDelivered.getPeak() / 1024.0, dataDelivered.getTotal())); - CurrentActor.get().message(VirtualHostMessages.STATS_MSGS(name, DELIVERED, messagesDelivered.getPeak(), messagesDelivered.getTotal())); - CurrentActor.get().message(VirtualHostMessages.STATS_DATA(name, RECEIVED, dataReceived.getPeak() / 1024.0, dataReceived.getTotal())); - CurrentActor.get().message(VirtualHostMessages.STATS_MSGS(name, RECEIVED, messagesReceived.getPeak(), messagesReceived.getTotal())); - } - } - - if (reset) - { - resetStatistics(); - } - - CurrentActor.remove(); + String name = vhost.getName(); + StatisticsCounter dataDelivered = vhost.getDataDeliveryStatistics(); + StatisticsCounter messagesDelivered = vhost.getMessageDeliveryStatistics(); + StatisticsCounter dataReceived = vhost.getDataReceiptStatistics(); + StatisticsCounter messagesReceived = vhost.getMessageReceiptStatistics(); + + CurrentActor.get().message(VirtualHostMessages.STATS_DATA(name, DELIVERED, dataDelivered.getPeak() / 1024.0, dataDelivered.getTotal())); + CurrentActor.get().message(VirtualHostMessages.STATS_MSGS(name, DELIVERED, messagesDelivered.getPeak(), messagesDelivered.getTotal())); + CurrentActor.get().message(VirtualHostMessages.STATS_DATA(name, RECEIVED, dataReceived.getPeak() / 1024.0, dataReceived.getTotal())); + CurrentActor.get().message(VirtualHostMessages.STATS_MSGS(name, RECEIVED, messagesReceived.getPeak(), messagesReceived.getTotal())); } } - _reportingTimer.scheduleAtFixedRate(new StatisticsReportingTask(), - report / 2, - report); + if (_reset) + { + resetStatistics(); + } + + CurrentActor.remove(); } } @@ -449,35 +522,49 @@ public abstract class ApplicationRegistry implements IApplicationRegistry } } - public void close() { if (_logger.isInfoEnabled()) { _logger.info("Shutting down ApplicationRegistry:" + this); } - - //Stop Statistics Reporting - if (_reportingTimer != null) + + //Set the Actor for Broker Shutdown + CurrentActor.set(new BrokerActor(getRootMessageLogger())); + try { - _reportingTimer.cancel(); - } + //Stop Statistics Reporting + if (_reportingTimer != null) + { + _reportingTimer.cancel(); + } - //Stop incoming connections - unbind(); + //Stop incoming connections + unbind(); - //Shutdown virtualhosts - close(_virtualHostRegistry); + //Shutdown virtualhosts + close(_virtualHostRegistry); - close(_authenticationManager); + close(_authenticationManager); - close(_qmfService); + close(_qmfService); - close(_pluginManager); + close(_pluginManager); - close(_managedObjectRegistry); + close(_managedObjectRegistry); - CurrentActor.get().message(BrokerMessages.STOPPED()); + BrokerConfig broker = getBroker(); + if(broker != null) + { + broker.getSystem().removeBroker(broker); + } + + CurrentActor.get().message(BrokerMessages.STOPPED()); + } + finally + { + CurrentActor.remove(); + } } private void unbind() @@ -654,4 +741,18 @@ public abstract class ApplicationRegistry implements IApplicationRegistry { _statisticsEnabled = enabled; } + + private void logStartupMessages(LogActor logActor) + { + logActor.message(BrokerMessages.STARTUP(QpidProperties.getReleaseVersion(), QpidProperties.getBuildVersion())); + + logActor.message(BrokerMessages.PLATFORM(System.getProperty("java.vendor"), + System.getProperty("java.runtime.version", System.getProperty("java.version")), + System.getProperty("os.name"), + System.getProperty("os.version"), + System.getProperty("os.arch"))); + + logActor.message(BrokerMessages.MAX_MEMORY(Runtime.getRuntime().maxMemory())); + } + } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/registry/BrokerConfigAdapter.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/registry/BrokerConfigAdapter.java index f77b8d2dfa..58fdc99dd3 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/registry/BrokerConfigAdapter.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/registry/BrokerConfigAdapter.java @@ -20,16 +20,21 @@ */ package org.apache.qpid.server.registry; -import org.apache.qpid.server.configuration.*; -import org.apache.qpid.server.virtualhost.VirtualHost; import org.apache.qpid.common.QpidProperties; import org.apache.qpid.common.ServerPropertyNames; +import org.apache.qpid.server.configuration.BrokerConfig; +import org.apache.qpid.server.configuration.BrokerConfigType; +import org.apache.qpid.server.configuration.ConfigStore; +import org.apache.qpid.server.configuration.ConfiguredObject; +import org.apache.qpid.server.configuration.SystemConfig; +import org.apache.qpid.server.configuration.VirtualHostConfig; +import org.apache.qpid.server.virtualhost.VirtualHost; import java.util.ArrayList; import java.util.Collections; -import java.util.UUID; import java.util.List; import java.util.Map; +import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; public class BrokerConfigAdapter implements BrokerConfig diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/registry/ConfigurationFileApplicationRegistry.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/registry/ConfigurationFileApplicationRegistry.java index 9121f8f927..b28e3d6c89 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/registry/ConfigurationFileApplicationRegistry.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/registry/ConfigurationFileApplicationRegistry.java @@ -20,16 +20,15 @@ */ package org.apache.qpid.server.registry; -import java.io.File; - import org.apache.commons.configuration.ConfigurationException; +import org.osgi.framework.BundleContext; + import org.apache.qpid.AMQException; import org.apache.qpid.server.configuration.ServerConfiguration; -import org.apache.qpid.server.logging.actors.BrokerActor; -import org.apache.qpid.server.logging.actors.CurrentActor; import org.apache.qpid.server.management.JMXManagedObjectRegistry; import org.apache.qpid.server.management.NoopManagedObjectRegistry; -import org.osgi.framework.BundleContext; + +import java.io.File; public class ConfigurationFileApplicationRegistry extends ApplicationRegistry { @@ -43,32 +42,16 @@ public class ConfigurationFileApplicationRegistry extends ApplicationRegistry super(new ServerConfiguration(configurationURL), bundleContext); } - @Override - public void close() - { - //Set the Actor for Broker Shutdown - CurrentActor.set(new BrokerActor(_rootMessageLogger)); - try - { - super.close(); - } - finally - { - CurrentActor.remove(); - } - } - - @Override protected void initialiseManagedObjectRegistry() throws AMQException { - if (_configuration.getManagementEnabled()) + if (getConfiguration().getManagementEnabled()) { - _managedObjectRegistry = new JMXManagedObjectRegistry(); + setManagedObjectRegistry(new JMXManagedObjectRegistry()); } else { - _managedObjectRegistry = new NoopManagedObjectRegistry(); + setManagedObjectRegistry(new NoopManagedObjectRegistry()); } } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/registry/IApplicationRegistry.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/registry/IApplicationRegistry.java index c27e0d19ec..59bf250590 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/registry/IApplicationRegistry.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/registry/IApplicationRegistry.java @@ -20,15 +20,12 @@ */ package org.apache.qpid.server.registry; -import java.net.InetSocketAddress; -import java.util.UUID; - import org.apache.qpid.qmf.QMFService; import org.apache.qpid.server.configuration.BrokerConfig; import org.apache.qpid.server.configuration.ConfigStore; +import org.apache.qpid.server.configuration.ConfigurationManager; import org.apache.qpid.server.configuration.ServerConfiguration; import org.apache.qpid.server.configuration.VirtualHostConfiguration; -import org.apache.qpid.server.configuration.ConfigurationManager; import org.apache.qpid.server.logging.RootMessageLogger; import org.apache.qpid.server.management.ManagedObjectRegistry; import org.apache.qpid.server.plugins.PluginManager; @@ -39,6 +36,9 @@ import org.apache.qpid.server.transport.QpidAcceptor; import org.apache.qpid.server.virtualhost.VirtualHost; import org.apache.qpid.server.virtualhost.VirtualHostRegistry; +import java.net.InetSocketAddress; +import java.util.UUID; + public interface IApplicationRegistry extends StatisticsGatherer { /** diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/AbstractPlugin.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/AbstractPlugin.java index ff80499bc2..704e50da5c 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/AbstractPlugin.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/AbstractPlugin.java @@ -20,8 +20,8 @@ */ package org.apache.qpid.server.security; -import org.apache.commons.configuration.ConfigurationException; import org.apache.log4j.Logger; + import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin; import org.apache.qpid.server.security.access.ObjectProperties; import org.apache.qpid.server.security.access.ObjectType; @@ -32,9 +32,9 @@ import org.apache.qpid.server.security.access.Operation; */ public abstract class AbstractPlugin implements SecurityPlugin { - protected final Logger _logger = Logger.getLogger(getClass()); + private final Logger _logger = Logger.getLogger(getClass()); - protected ConfigurationPlugin _config; + private ConfigurationPlugin _config; public Result getDefault() { @@ -50,4 +50,8 @@ public abstract class AbstractPlugin implements SecurityPlugin _config = config; } + public ConfigurationPlugin getConfig() + { + return _config; + } } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/AbstractProxyPlugin.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/AbstractProxyPlugin.java index ec11e2d39c..236931e8cd 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/AbstractProxyPlugin.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/AbstractProxyPlugin.java @@ -20,7 +20,6 @@ */ package org.apache.qpid.server.security; -import org.apache.commons.configuration.Configuration; import org.apache.qpid.server.security.access.ObjectProperties; import org.apache.qpid.server.security.access.ObjectType; import org.apache.qpid.server.security.access.Operation; @@ -28,8 +27,6 @@ import org.apache.qpid.server.security.access.Operation; /** * This {@link SecurityPlugin} proxies the authorise calls to a serries of methods, one per {@link Operation}. * - * Plugins that extend this class should override the relevant authorise method and implement their own - * {@link #setConfiguration(Configuration)} method. */ public abstract class AbstractProxyPlugin extends AbstractPlugin { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/AuthorizationHolder.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/AuthorizationHolder.java index 3d8c77a86f..8f3bdf7738 100755 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/AuthorizationHolder.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/AuthorizationHolder.java @@ -20,12 +20,8 @@ */ package org.apache.qpid.server.security; -import java.security.Principal; - import javax.security.auth.Subject; - -import org.apache.qpid.server.security.auth.sasl.GroupPrincipal; -import org.apache.qpid.server.security.auth.sasl.UsernamePrincipal; +import java.security.Principal; /** * Represents the authorization of the logged on user. @@ -35,8 +31,8 @@ public interface AuthorizationHolder { /** * Returns the {@link Subject} of the authorized user. This is guaranteed to - * contain at least one {@link UsernamePrincipal}, representing the the identity - * used when the user logged on to the application, and zero or more {@link GroupPrincipal} + * contain at least one {@link org.apache.qpid.server.security.auth.sasl.UsernamePrincipal}, representing the the identity + * used when the user logged on to the application, and zero or more {@link org.apache.qpid.server.security.auth.sasl.GroupPrincipal} * representing the group(s) to which the user belongs. * * @return the Subject diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/SecurityManager.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/SecurityManager.java index 2a1ae8a870..436660cfaf 100755 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/SecurityManager.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/SecurityManager.java @@ -18,6 +18,19 @@ */ package org.apache.qpid.server.security; +import org.apache.commons.configuration.Configuration; +import org.apache.commons.configuration.ConfigurationException; +import org.apache.log4j.Logger; + +import org.apache.qpid.framing.AMQShortString; +import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin; +import org.apache.qpid.server.configuration.plugins.ConfigurationPluginFactory; +import org.apache.qpid.server.exchange.Exchange; +import org.apache.qpid.server.plugins.PluginManager; +import org.apache.qpid.server.queue.AMQQueue; +import org.apache.qpid.server.security.access.ObjectProperties; +import org.apache.qpid.server.security.access.Operation; + import static org.apache.qpid.server.security.access.ObjectType.EXCHANGE; import static org.apache.qpid.server.security.access.ObjectType.METHOD; import static org.apache.qpid.server.security.access.ObjectType.QUEUE; @@ -30,26 +43,17 @@ import static org.apache.qpid.server.security.access.Operation.PUBLISH; import static org.apache.qpid.server.security.access.Operation.PURGE; import static org.apache.qpid.server.security.access.Operation.UNBIND; +import javax.security.auth.Subject; import java.net.SocketAddress; -import java.security.Principal; -import java.util.*; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; -import javax.security.auth.Subject; - -import org.apache.commons.configuration.Configuration; -import org.apache.commons.configuration.ConfigurationException; -import org.apache.log4j.Logger; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin; -import org.apache.qpid.server.configuration.plugins.ConfigurationPluginFactory; -import org.apache.qpid.server.exchange.Exchange; -import org.apache.qpid.server.plugins.PluginManager; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.security.access.ObjectProperties; -import org.apache.qpid.server.security.access.Operation; - /** * The security manager contains references to all loaded {@link SecurityPlugin}s and delegates security decisions to them based * on virtual host name. The plugins can be external OSGi .jar files that export the required classes or just internal @@ -61,7 +65,7 @@ public class SecurityManager { private static final Logger _logger = Logger.getLogger(SecurityManager.class); - /** Container for the {@link Principal} that is using to this thread. */ + /** Container for the {@link java.security.Principal} that is using to this thread. */ private static final ThreadLocal _subject = new ThreadLocal(); private static final ThreadLocal _accessChecksDisabled = new ThreadLocal() { @@ -101,7 +105,7 @@ public class SecurityManager public void validateConfiguration() throws ConfigurationException { - if (_configuration.isEmpty()) + if (getConfig().isEmpty()) { throw new ConfigurationException("security section is incomplete, no elements found."); } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/SecurityPluginActivator.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/SecurityPluginActivator.java index 5ee7833c4c..21c2d1cda5 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/SecurityPluginActivator.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/SecurityPluginActivator.java @@ -21,10 +21,11 @@ package org.apache.qpid.server.security; import org.apache.log4j.Logger; -import org.apache.qpid.server.configuration.plugins.ConfigurationPluginFactory; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; +import org.apache.qpid.server.configuration.plugins.ConfigurationPluginFactory; + /** * An OSGi {@link BundleActivator} that loads a {@link SecurityPluginFactory}. */ diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/access/ObjectProperties.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/access/ObjectProperties.java index 8a52d31f97..a9ec4d1647 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/access/ObjectProperties.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/access/ObjectProperties.java @@ -18,13 +18,17 @@ */ package org.apache.qpid.server.security.access; -import java.util.*; - import org.apache.commons.lang.StringUtils; + import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.server.exchange.Exchange; import org.apache.qpid.server.queue.AMQQueue; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; + /** * An set of properties for an access control v2 rule {@link ObjectType}. * @@ -315,19 +319,28 @@ public class ObjectProperties || ruleValue.equals(STAR) || (ruleValue.endsWith(STAR) && thisValue != null - && thisValue.length() > ruleValue.length() - && thisValue.startsWith(ruleValue.substring(0, ruleValue.length() - 2))); + && thisValue.length() >= ruleValue.length() - 1 + && thisValue.startsWith(ruleValue.substring(0, ruleValue.length() - 1))); } @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) + { + return true; + } + if (o == null || getClass() != o.getClass()) + { + return false; + } ObjectProperties that = (ObjectProperties) o; - if (_properties != null ? !_properties.equals(that._properties) : that._properties != null) return false; + if (_properties != null ? !_properties.equals(that._properties) : that._properties != null) + { + return false; + } return true; } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/access/ObjectType.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/access/ObjectType.java index 69c7ff185a..90ecd1dd17 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/access/ObjectType.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/access/ObjectType.java @@ -18,7 +18,15 @@ */ package org.apache.qpid.server.security.access; -import static org.apache.qpid.server.security.access.Operation.*; +import static org.apache.qpid.server.security.access.Operation.ACCESS; +import static org.apache.qpid.server.security.access.Operation.BIND; +import static org.apache.qpid.server.security.access.Operation.CONSUME; +import static org.apache.qpid.server.security.access.Operation.CREATE; +import static org.apache.qpid.server.security.access.Operation.DELETE; +import static org.apache.qpid.server.security.access.Operation.PUBLISH; +import static org.apache.qpid.server.security.access.Operation.PURGE; +import static org.apache.qpid.server.security.access.Operation.UNBIND; +import static org.apache.qpid.server.security.access.Operation.UPDATE; import java.util.EnumSet; import java.util.Set; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/access/plugins/AllowAll.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/access/plugins/AllowAll.java deleted file mode 100644 index db18a89231..0000000000 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/access/plugins/AllowAll.java +++ /dev/null @@ -1,99 +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.security.access.plugins; - -import java.util.Arrays; -import java.util.List; - -import org.apache.commons.configuration.Configuration; -import org.apache.commons.configuration.ConfigurationException; -import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin; -import org.apache.qpid.server.configuration.plugins.ConfigurationPluginFactory; -import org.apache.qpid.server.security.Result; -import org.apache.qpid.server.security.SecurityPluginFactory; - -/** Always allow. */ -public class AllowAll extends BasicPlugin -{ - public static class AllowAllConfiguration extends ConfigurationPlugin { - public static final ConfigurationPluginFactory FACTORY = new ConfigurationPluginFactory() - { - public List getParentPaths() - { - return Arrays.asList("security.allow-all", "virtualhosts.virtualhost.security.allow-all"); - } - - public ConfigurationPlugin newInstance(String path, Configuration config) throws ConfigurationException - { - ConfigurationPlugin instance = new AllowAllConfiguration(); - instance.setConfiguration(path, config); - return instance; - } - }; - - public String[] getElementsProcessed() - { - return new String[] { "" }; - } - - public void validateConfiguration() throws ConfigurationException - { -// if (!_configuration.isEmpty()) -// { -// throw new ConfigurationException("allow-all section takes no elements."); -// } - } - - } - - public static final SecurityPluginFactory FACTORY = new SecurityPluginFactory() - { - public AllowAll newInstance(ConfigurationPlugin config) throws ConfigurationException - { - AllowAllConfiguration configuration = config.getConfiguration(AllowAllConfiguration.class.getName()); - - // If there is no configuration for this plugin then don't load it. - if (configuration == null) - { - return null; - } - - AllowAll plugin = new AllowAll(); - plugin.configure(configuration); - return plugin; - } - - public String getPluginName() - { - return AllowAll.class.getName(); - } - - public Class getPluginClass() - { - return AllowAll.class; - } - }; - - @Override - public Result getDefault() - { - return Result.ALLOWED; - } - -} diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/access/plugins/BasicPlugin.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/access/plugins/BasicPlugin.java index f3161551dc..4df135a4ca 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/access/plugins/BasicPlugin.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/access/plugins/BasicPlugin.java @@ -20,16 +20,14 @@ */ package org.apache.qpid.server.security.access.plugins; -import org.apache.commons.configuration.ConfigurationException; import org.apache.qpid.server.security.AbstractPlugin; import org.apache.qpid.server.security.Result; -import org.apache.qpid.server.security.SecurityPlugin; import org.apache.qpid.server.security.access.ObjectProperties; import org.apache.qpid.server.security.access.ObjectType; import org.apache.qpid.server.security.access.Operation; /** - * This {@link SecurityPlugin} simply abstains from all authorisation requests and ignores configuration. + * This {@link org.apache.qpid.server.security.SecurityPlugin} simply abstains from all authorisation requests and ignores configuration. */ public abstract class BasicPlugin extends AbstractPlugin { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/access/plugins/DenyAll.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/access/plugins/DenyAll.java deleted file mode 100644 index 6c0fb1eaa4..0000000000 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/access/plugins/DenyAll.java +++ /dev/null @@ -1,99 +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.security.access.plugins; - -import java.util.Arrays; -import java.util.List; - -import org.apache.commons.configuration.Configuration; -import org.apache.commons.configuration.ConfigurationException; -import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin; -import org.apache.qpid.server.configuration.plugins.ConfigurationPluginFactory; -import org.apache.qpid.server.security.Result; -import org.apache.qpid.server.security.SecurityPluginFactory; - -/** Always Deny. */ -public class DenyAll extends BasicPlugin -{ - public static class DenyAllConfiguration extends ConfigurationPlugin { - public static final ConfigurationPluginFactory FACTORY = new ConfigurationPluginFactory() - { - public List getParentPaths() - { - return Arrays.asList("security.deny-all", "virtualhosts.virtualhost.security.deny-all"); - } - - public ConfigurationPlugin newInstance(String path, Configuration config) throws ConfigurationException - { - ConfigurationPlugin instance = new DenyAllConfiguration(); - instance.setConfiguration(path, config); - return instance; - } - }; - - public String[] getElementsProcessed() - { - return new String[] { "" }; - } - - public void validateConfiguration() throws ConfigurationException - { - if (!_configuration.isEmpty()) - { - throw new ConfigurationException("deny-all section takes no elements."); - } - } - - } - - public static final SecurityPluginFactory FACTORY = new SecurityPluginFactory() - { - public DenyAll newInstance(ConfigurationPlugin config) throws ConfigurationException - { - DenyAllConfiguration configuration = config.getConfiguration(DenyAllConfiguration.class.getName()); - - // If there is no configuration for this plugin then don't load it. - if (configuration == null) - { - return null; - } - - DenyAll plugin = new DenyAll(); - plugin.configure(configuration); - return plugin; - } - - public String getPluginName() - { - return DenyAll.class.getName(); - } - - public Class getPluginClass() - { - return DenyAll.class; - } - }; - - @Override - public Result getDefault() - { - return Result.DENIED; - } - -} diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/access/plugins/LegacyAccess.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/access/plugins/LegacyAccess.java index bd99cdd1fa..4b7a2fb457 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/access/plugins/LegacyAccess.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/access/plugins/LegacyAccess.java @@ -18,18 +18,19 @@ */ package org.apache.qpid.server.security.access.plugins; -import java.util.Arrays; -import java.util.List; - import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.ConfigurationException; + import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin; -import org.apache.qpid.server.configuration.VirtualHostConfiguration; -import org.apache.qpid.server.configuration.ServerConfiguration; import org.apache.qpid.server.configuration.plugins.ConfigurationPluginFactory; import org.apache.qpid.server.security.SecurityPluginFactory; -/** Always Abstain. */ +import java.util.Arrays; +import java.util.List; + +/** + * The LegacyAccess plugin is used internally and simply ignores legacy elements of the configuration file. + */ public class LegacyAccess extends BasicPlugin { public static class LegacyAccessConfiguration extends ConfigurationPlugin { @@ -37,9 +38,7 @@ public class LegacyAccess extends BasicPlugin { public List getParentPaths() { - return Arrays.asList("security.jmx", "virtualhosts.virtualhost.security.jmx", - "security.msg-auth", "virtualhosts.virtualhost.security.msg-auth", - "security.principal-databases", "virtualhosts.virtualhost.security.principal-databases"); + return Arrays.asList("security.msg-auth", "virtualhosts.virtualhost.security.msg-auth"); } public ConfigurationPlugin newInstance(String path, Configuration config) throws ConfigurationException diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/AuthenticationResult.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/AuthenticationResult.java index 8c2d60a660..949c0f2b89 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/AuthenticationResult.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/AuthenticationResult.java @@ -53,8 +53,8 @@ public class AuthenticationResult ERROR } - public final AuthenticationStatus _status; - public final byte[] _challenge; + private final AuthenticationStatus _status; + private final byte[] _challenge; private final Exception _cause; private final Subject _subject; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/AbstractPasswordFilePrincipalDatabase.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/AbstractPasswordFilePrincipalDatabase.java new file mode 100644 index 0000000000..7088fae50c --- /dev/null +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/AbstractPasswordFilePrincipalDatabase.java @@ -0,0 +1,484 @@ +/* + * + * 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.security.auth.database; + +import org.apache.log4j.Logger; +import org.apache.qpid.server.security.auth.sasl.AuthenticationProviderInitialiser; +import org.apache.qpid.server.security.auth.sasl.UsernamePasswordInitialiser; +import org.apache.qpid.server.security.auth.sasl.UsernamePrincipal; + +import javax.security.auth.callback.PasswordCallback; +import javax.security.auth.login.AccountNotFoundException; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.io.PrintStream; +import java.security.Principal; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.concurrent.locks.ReentrantLock; +import java.util.regex.Pattern; + +public abstract class AbstractPasswordFilePrincipalDatabase implements PrincipalDatabase +{ + private final Pattern _regexp = Pattern.compile(":"); + + private final Map _saslServers = + new HashMap(); + + protected static final String DEFAULT_ENCODING = "utf-8"; + private final Map _userMap = new HashMap(); + private final ReentrantLock _userUpdate = new ReentrantLock(); + private final Random _random = new Random(); + private File _passwordFile; + + + protected AbstractPasswordFilePrincipalDatabase(UsernamePasswordInitialiser... initialisers) + { + for(UsernamePasswordInitialiser initialiser : initialisers) + { + initialiser.initialise(this); + _saslServers.put(initialiser.getMechanismName(), initialiser); + } + } + + public final void setPasswordFile(String passwordFile) throws IOException + { + File f = new File(passwordFile); + getLogger().info("PasswordFile using file " + f.getAbsolutePath()); + _passwordFile = f; + if (!f.exists()) + { + throw new FileNotFoundException("Cannot find password file " + f); + } + if (!f.canRead()) + { + throw new FileNotFoundException("Cannot read password file " + f + + ". Check permissions."); + } + + loadPasswordFile(); + } + + /** + * SASL Callback Mechanism - sets the Password in the PasswordCallback based on the value in the PasswordFile + * If you want to change the password for a user, use updatePassword instead. + * + * @param principal The Principal to set the password for + * @param callback The PasswordCallback to call setPassword on + * + * @throws javax.security.auth.login.AccountNotFoundException If the Principal cannot be found in this Database + */ + public final void setPassword(Principal principal, PasswordCallback callback) throws AccountNotFoundException + { + if (_passwordFile == null) + { + throw new AccountNotFoundException("Unable to locate principal since no password file was specified during initialisation"); + } + if (principal == null) + { + throw new IllegalArgumentException("principal must not be null"); + } + char[] pwd = lookupPassword(principal.getName()); + + if (pwd != null) + { + callback.setPassword(pwd); + } + else + { + throw new AccountNotFoundException("No account found for principal " + principal); + } + } + + + /** + * Looks up the password for a specified user in the password file. Note this code is not secure since it + * creates strings of passwords. It should be modified to create only char arrays which get nulled out. + * + * @param name The principal name to lookup + * + * @return a char[] for use in SASL. + */ + protected final char[] lookupPassword(String name) + { + U user = _userMap.get(name); + if (user == null) + { + return null; + } + else + { + return user.getPassword(); + } + } + + protected boolean compareCharArray(char[] a, char[] b) + { + boolean equal = false; + if (a.length == b.length) + { + equal = true; + int index = 0; + while (equal && index < a.length) + { + equal = a[index] == b[index]; + index++; + } + } + return equal; + } + + /** + * Changes the password for the specified user + * + * @param principal to change the password for + * @param password plaintext password to set the password too + */ + public boolean updatePassword(Principal principal, char[] password) throws AccountNotFoundException + { + U user = _userMap.get(principal.getName()); + + if (user == null) + { + throw new AccountNotFoundException(principal.getName()); + } + + char[] orig = user.getPassword(); + _userUpdate.lock(); + try + { + user.setPassword(password); + + savePasswordFile(); + + return true; + } + catch (IOException e) + { + getLogger().error("Unable to save password file due to '" + e.getMessage() + + "', password change for user '" + principal + "' discarded"); + //revert the password change + user.restorePassword(orig); + + return false; + } + finally + { + _userUpdate.unlock(); + } + } + + + private void loadPasswordFile() throws IOException + { + try + { + _userUpdate.lock(); + _userMap.clear(); + + BufferedReader reader = null; + try + { + reader = new BufferedReader(new FileReader(_passwordFile)); + String line; + + while ((line = reader.readLine()) != null) + { + String[] result = _regexp.split(line); + if (result == null || result.length < 2 || result[0].startsWith("#")) + { + continue; + } + + U user = createUserFromFileData(result); + getLogger().info("Created user:" + user); + _userMap.put(user.getName(), user); + } + } + finally + { + if (reader != null) + { + reader.close(); + } + } + } + finally + { + _userUpdate.unlock(); + } + } + + protected abstract U createUserFromFileData(String[] result); + + + protected abstract Logger getLogger(); + + protected File createTempFileOnSameFilesystem() + { + File liveFile = _passwordFile; + File tmp; + + do + { + tmp = new File(liveFile.getPath() + _random.nextInt() + ".tmp"); + } + while(tmp.exists()); + + tmp.deleteOnExit(); + return tmp; + } + + protected void swapTempFileToLive(final File temp) throws IOException + { + File live = _passwordFile; + // Remove any existing ".old" file + final File old = new File(live.getAbsoluteFile() + ".old"); + if (old.exists()) + { + old.delete(); + } + + // Create an new ".old" file + if(!live.renameTo(old)) + { + //unable to rename the existing file to the backup name + getLogger().error("Could not backup the existing password file"); + throw new IOException("Could not backup the existing password file"); + } + + // Move temp file to be the new "live" file + if(!temp.renameTo(live)) + { + //failed to rename the new file to the required filename + if(!old.renameTo(live)) + { + //unable to return the backup to required filename + getLogger().error( + "Could not rename the new password file into place, and unable to restore original file"); + throw new IOException("Could not rename the new password file into place, and unable to restore original file"); + } + + getLogger().error("Could not rename the new password file into place"); + throw new IOException("Could not rename the new password file into place"); + } + } + + protected void savePasswordFile() throws IOException + { + try + { + _userUpdate.lock(); + + BufferedReader reader = null; + PrintStream writer = null; + + File tmp = createTempFileOnSameFilesystem(); + + try + { + writer = new PrintStream(tmp); + reader = new BufferedReader(new FileReader(_passwordFile)); + String line; + + while ((line = reader.readLine()) != null) + { + String[] result = _regexp.split(line); + if (result == null || result.length < 2 || result[0].startsWith("#")) + { + writer.write(line.getBytes(DEFAULT_ENCODING)); + writer.println(); + continue; + } + + U user = _userMap.get(result[0]); + + if (user == null) + { + writer.write(line.getBytes(DEFAULT_ENCODING)); + writer.println(); + } + else if (!user.isDeleted()) + { + if (!user.isModified()) + { + writer.write(line.getBytes(DEFAULT_ENCODING)); + writer.println(); + } + else + { + byte[] encodedPassword = user.getEncodedPassword(); + + writer.write((user.getName() + ":").getBytes(DEFAULT_ENCODING)); + writer.write(encodedPassword); + writer.println(); + + user.saved(); + } + } + } + + for (U user : _userMap.values()) + { + if (user.isModified()) + { + byte[] encodedPassword; + encodedPassword = user.getEncodedPassword(); + writer.write((user.getName() + ":").getBytes(DEFAULT_ENCODING)); + writer.write(encodedPassword); + writer.println(); + user.saved(); + } + } + } + catch(IOException e) + { + getLogger().error("Unable to create the new password file: " + e); + throw new IOException("Unable to create the new password file",e); + } + finally + { + + try + { + if (reader != null) + { + reader.close(); + } + } + finally + { + if (writer != null) + { + writer.close(); + } + } + + } + + swapTempFileToLive(tmp); + } + finally + { + _userUpdate.unlock(); + } + } + + protected abstract U createUserFromPassword(Principal principal, char[] passwd); + + + public void reload() throws IOException + { + loadPasswordFile(); + } + + public Map getMechanisms() + { + return _saslServers; + } + + public List getUsers() + { + return new LinkedList(_userMap.values()); + } + + public Principal getUser(String username) + { + if (_userMap.containsKey(username)) + { + return new UsernamePrincipal(username); + } + return null; + } + + public boolean deletePrincipal(Principal principal) throws AccountNotFoundException + { + U user = _userMap.get(principal.getName()); + + if (user == null) + { + throw new AccountNotFoundException(principal.getName()); + } + + try + { + _userUpdate.lock(); + user.delete(); + + try + { + savePasswordFile(); + } + catch (IOException e) + { + getLogger().error("Unable to remove user '" + user.getName() + "' from password file."); + return false; + } + + _userMap.remove(user.getName()); + } + finally + { + _userUpdate.unlock(); + } + + return true; + } + + public boolean createPrincipal(Principal principal, char[] password) + { + if (_userMap.get(principal.getName()) != null) + { + return false; + } + + U user = createUserFromPassword(principal, password); + + + try + { + _userUpdate.lock(); + _userMap.put(user.getName(), user); + + try + { + savePasswordFile(); + return true; + } + catch (IOException e) + { + //remove the use on failure. + _userMap.remove(user.getName()); + return false; + } + } + finally + { + _userUpdate.unlock(); + } + } +} diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/Base64MD5PasswordFilePrincipalDatabase.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/Base64MD5PasswordFilePrincipalDatabase.java index 5a92b33e43..63eb768035 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/Base64MD5PasswordFilePrincipalDatabase.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/Base64MD5PasswordFilePrincipalDatabase.java @@ -21,29 +21,12 @@ package org.apache.qpid.server.security.auth.database; import org.apache.log4j.Logger; -import org.apache.qpid.server.security.auth.management.AMQUserManagementMBean; -import org.apache.qpid.server.security.auth.sasl.AuthenticationProviderInitialiser; -import org.apache.qpid.server.security.auth.sasl.UsernamePrincipal; -import org.apache.qpid.server.security.auth.sasl.crammd5.CRAMMD5HexInitialiser; + import org.apache.qpid.server.security.auth.sasl.crammd5.CRAMMD5HashedInitialiser; -import org.apache.qpid.util.FileUtils; +import org.apache.qpid.server.security.auth.sasl.crammd5.CRAMMD5HexInitialiser; -import javax.security.auth.callback.PasswordCallback; import javax.security.auth.login.AccountNotFoundException; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.io.PrintStream; import java.security.Principal; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Random; -import java.util.concurrent.locks.ReentrantLock; -import java.util.regex.Pattern; /** * Represents a user database where the account information is stored in a simple flat file. @@ -52,100 +35,19 @@ import java.util.regex.Pattern; * * where a carriage return separates each username/password pair. Passwords are assumed to be in plain text. */ -public class Base64MD5PasswordFilePrincipalDatabase implements PrincipalDatabase +public class Base64MD5PasswordFilePrincipalDatabase extends AbstractPasswordFilePrincipalDatabase { - private static final Logger _logger = Logger.getLogger(Base64MD5PasswordFilePrincipalDatabase.class); - - private File _passwordFile; - - private Pattern _regexp = Pattern.compile(":"); - - private Map _saslServers; - - AMQUserManagementMBean _mbean; - public static final String DEFAULT_ENCODING = "utf-8"; - private Map _users = new HashMap(); - private ReentrantLock _userUpdate = new ReentrantLock(); + private final Logger _logger = Logger.getLogger(Base64MD5PasswordFilePrincipalDatabase.class); public Base64MD5PasswordFilePrincipalDatabase() { - _saslServers = new HashMap(); - /** * Create Authenticators for MD5 Password file. */ + super(new CRAMMD5HashedInitialiser(), new CRAMMD5HexInitialiser()); - // Accept Plain incomming and hash it for comparison to the file. - CRAMMD5HashedInitialiser cram = new CRAMMD5HashedInitialiser(); - cram.initialise(this); - _saslServers.put(cram.getMechanismName(), cram); - - //Add the Hex initialiser - CRAMMD5HexInitialiser cramHex = new CRAMMD5HexInitialiser(); - cramHex.initialise(this); - _saslServers.put(cramHex.getMechanismName(), cramHex); - - //fixme The PDs should setup a PD Mangement MBean -// try -// { -// _mbean = new AMQUserManagementMBean(); -// _mbean.setPrincipalDatabase(this); -// } -// catch (JMException e) -// { -// _logger.warn("User management disabled as unable to create MBean:" + e); -// } - } - - public void setPasswordFile(String passwordFile) throws IOException - { - File f = new File(passwordFile); - _logger.info("PasswordFilePrincipalDatabase using file " + f.getAbsolutePath()); - _passwordFile = f; - if (!f.exists()) - { - throw new FileNotFoundException("Cannot find password file " + f); - } - if (!f.canRead()) - { - throw new FileNotFoundException("Cannot read password file " + f + - ". Check permissions."); - } - - loadPasswordFile(); } - /** - * SASL Callback Mechanism - sets the Password in the PasswordCallback based on the value in the PasswordFile - * If you want to change the password for a user, use updatePassword instead. - * - * @param principal The Principal to set the password for - * @param callback The PasswordCallback to call setPassword on - * - * @throws AccountNotFoundException If the Principal cannont be found in this Database - */ - public void setPassword(Principal principal, PasswordCallback callback) throws AccountNotFoundException - { - if (_passwordFile == null) - { - throw new AccountNotFoundException("Unable to locate principal since no password file was specified during initialisation"); - } - if (principal == null) - { - throw new IllegalArgumentException("principal must not be null"); - } - - char[] pwd = lookupPassword(principal.getName()); - - if (pwd != null) - { - callback.setPassword(pwd); - } - else - { - throw new AccountNotFoundException("No account found for principal " + principal); - } - } /** * Used to verify that the presented Password is correct. Currently only used by Management Console @@ -180,7 +82,7 @@ public class Base64MD5PasswordFilePrincipalDatabase implements PrincipalDatabase } catch (Exception e1) { - _logger.warn("Unable to hash password for user '" + principal + "' for comparison"); + getLogger().warn("Unable to hash password for user '" + principal + "' for comparison"); return false; } @@ -194,374 +96,21 @@ public class Base64MD5PasswordFilePrincipalDatabase implements PrincipalDatabase return compareCharArray(pwd, hashedPassword); } - - private boolean compareCharArray(char[] a, char[] b) - { - boolean equal = false; - if (a.length == b.length) - { - equal = true; - int index = 0; - while (equal && index < a.length) - { - equal = a[index] == b[index]; - index++; - } - } - return equal; - } - /** - * Changes the password for the specified user - * - * @param principal to change the password for - * @param password plaintext password to set the password too - */ - public boolean updatePassword(Principal principal, char[] password) throws AccountNotFoundException + protected HashedUser createUserFromPassword(Principal principal, char[] passwd) { - HashedUser user = _users.get(principal.getName()); - - if (user == null) - { - throw new AccountNotFoundException(principal.getName()); - } - - try - { - try - { - _userUpdate.lock(); - char[] orig = user.getPassword(); - user.setPassword(password,false); - - try - { - savePasswordFile(); - } - catch (IOException e) - { - _logger.error("Unable to save password file, password change for user'" - + principal + "' will revert at restart"); - //revert the password change - user.setPassword(orig,true); - return false; - } - return true; - } - finally - { - _userUpdate.unlock(); - } - } - catch (Exception e) - { - return false; - } + return new HashedUser(principal.getName(), passwd); } - public boolean createPrincipal(Principal principal, char[] password) - { - if (_users.get(principal.getName()) != null) - { - return false; - } - HashedUser user; - try - { - user = new HashedUser(principal.getName(), password); - } - catch (Exception e1) - { - _logger.warn("Unable to create new user '" + principal.getName() + "'"); - return false; - } - - - try - { - _userUpdate.lock(); - _users.put(user.getName(), user); - - try - { - savePasswordFile(); - return true; - } - catch (IOException e) - { - //remove the use on failure. - _users.remove(user.getName()); - return false; - } - } - finally - { - _userUpdate.unlock(); - } - } - - public boolean deletePrincipal(Principal principal) throws AccountNotFoundException - { - HashedUser user = _users.get(principal.getName()); - - if (user == null) - { - throw new AccountNotFoundException(principal.getName()); - } - - try - { - _userUpdate.lock(); - user.delete(); - - try - { - savePasswordFile(); - } - catch (IOException e) - { - _logger.warn("Unable to remove user '" + user.getName() + "' from password file."); - return false; - } - - _users.remove(user.getName()); - } - finally - { - _userUpdate.unlock(); - } - - return true; - } - - public Map getMechanisms() - { - return _saslServers; - } - - public List getUsers() - { - return new LinkedList(_users.values()); - } - - public Principal getUser(String username) - { - if (_users.containsKey(username)) - { - return new UsernamePrincipal(username); - } - return null; - } - - /** - * Looks up the password for a specified user in the password file. Note this code is not secure since it - * creates strings of passwords. It should be modified to create only char arrays which get nulled out. - * - * @param name The principal name to lookup - * - * @return a char[] for use in SASL. - */ - private char[] lookupPassword(String name) + protected HashedUser createUserFromFileData(String[] result) { - HashedUser user = _users.get(name); - if (user == null) - { - return null; - } - else - { - return user.getPassword(); - } - } - - private void loadPasswordFile() throws IOException - { - try - { - _userUpdate.lock(); - _users.clear(); - - BufferedReader reader = null; - try - { - reader = new BufferedReader(new FileReader(_passwordFile)); - String line; - - while ((line = reader.readLine()) != null) - { - String[] result = _regexp.split(line); - if (result == null || result.length < 2 || result[0].startsWith("#")) - { - continue; - } - - HashedUser user = new HashedUser(result); - _logger.info("Created user:" + user); - _users.put(user.getName(), user); - } - } - finally - { - if (reader != null) - { - reader.close(); - } - } - } - finally - { - _userUpdate.unlock(); - } - } - - private void savePasswordFile() throws IOException - { - try - { - _userUpdate.lock(); - - BufferedReader reader = null; - PrintStream writer = null; - - Random r = new Random(); - File tmp; - do - { - tmp = new File(_passwordFile.getPath() + r.nextInt() + ".tmp"); - } - while(tmp.exists()); - - tmp.deleteOnExit(); - - try - { - writer = new PrintStream(tmp); - reader = new BufferedReader(new FileReader(_passwordFile)); - String line; - - while ((line = reader.readLine()) != null) - { - String[] result = _regexp.split(line); - if (result == null || result.length < 2 || result[0].startsWith("#")) - { - writer.write(line.getBytes(DEFAULT_ENCODING)); - writer.println(); - continue; - } - - HashedUser user = _users.get(result[0]); - - if (user == null) - { - writer.write(line.getBytes(DEFAULT_ENCODING)); - writer.println(); - } - else if (!user.isDeleted()) - { - if (!user.isModified()) - { - writer.write(line.getBytes(DEFAULT_ENCODING)); - writer.println(); - } - else - { - try - { - byte[] encodedPassword = user.getEncodedPassword(); - - writer.write((user.getName() + ":").getBytes(DEFAULT_ENCODING)); - writer.write(encodedPassword); - writer.println(); - - user.saved(); - } - catch (Exception e) - { - _logger.warn("Unable to encode new password reverting to old password."); - writer.write(line.getBytes(DEFAULT_ENCODING)); - writer.println(); - } - } - } - } - - for (HashedUser user : _users.values()) - { - if (user.isModified()) - { - byte[] encodedPassword; - try - { - encodedPassword = user.getEncodedPassword(); - writer.write((user.getName() + ":").getBytes(DEFAULT_ENCODING)); - writer.write(encodedPassword); - writer.println(); - user.saved(); - } - catch (Exception e) - { - _logger.warn("Unable to get Encoded password for user'" + user.getName() + "' password not saved"); - } - } - } - } - catch(IOException e) - { - _logger.error("Unable to create the new password file: " + e); - throw new IOException("Unable to create the new password file" + e); - } - finally - { - if (reader != null) - { - reader.close(); - } - - if (writer != null) - { - writer.close(); - } - } - - // Swap temp file to main password file. - File old = new File(_passwordFile.getAbsoluteFile() + ".old"); - if (old.exists()) - { - old.delete(); - } - - if(!_passwordFile.renameTo(old)) - { - //unable to rename the existing file to the backup name - _logger.error("Could not backup the existing password file"); - throw new IOException("Could not backup the existing password file"); - } - - if(!tmp.renameTo(_passwordFile)) - { - //failed to rename the new file to the required filename - - if(!old.renameTo(_passwordFile)) - { - //unable to return the backup to required filename - _logger.error("Could not rename the new password file into place, and unable to restore original file"); - throw new IOException("Could not rename the new password file into place, and unable to restore original file"); - } - - _logger.error("Could not rename the new password file into place"); - throw new IOException("Could not rename the new password file into place"); - } - } - finally - { - _userUpdate.unlock(); - } + return new HashedUser(result); } - public void reload() throws IOException + protected Logger getLogger() { - loadPasswordFile(); + return _logger; } } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/HashedUser.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/HashedUser.java index 3690e7f92a..b9de1587b5 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/HashedUser.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/HashedUser.java @@ -20,26 +20,25 @@ */ package org.apache.qpid.server.security.auth.database; -import org.apache.commons.codec.EncoderException; import org.apache.commons.codec.binary.Base64; import org.apache.log4j.Logger; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; -import java.security.Principal; -public class HashedUser implements Principal + +public class HashedUser implements PasswordPrincipal { private static final Logger _logger = Logger.getLogger(HashedUser.class); - String _name; - char[] _password; - byte[] _encodedPassword = null; + private String _name; + private char[] _password; + private byte[] _encodedPassword = null; private boolean _modified = false; private boolean _deleted = false; - HashedUser(String[] data) throws UnsupportedEncodingException + HashedUser(String[] data) { if (data.length != 2) { @@ -48,7 +47,15 @@ public class HashedUser implements Principal _name = data[0]; - byte[] encoded_password = data[1].getBytes(Base64MD5PasswordFilePrincipalDatabase.DEFAULT_ENCODING); + byte[] encoded_password; + try + { + encoded_password = data[1].getBytes(Base64MD5PasswordFilePrincipalDatabase.DEFAULT_ENCODING); + } + catch (UnsupportedEncodingException e) + { + throw new RuntimeException("MD5 encoding not supported, even though the Java standard requires it",e); + } Base64 b64 = new Base64(); byte[] decoded = b64.decode(encoded_password); @@ -64,15 +71,23 @@ public class HashedUser implements Principal } } - public HashedUser(String name, char[] password) throws UnsupportedEncodingException, NoSuchAlgorithmException + public HashedUser(String name, char[] password) { _name = name; setPassword(password,false); } - public static byte[] getMD5(byte[] data) throws NoSuchAlgorithmException, UnsupportedEncodingException + public static byte[] getMD5(byte[] data) { - MessageDigest md = MessageDigest.getInstance("MD5"); + MessageDigest md = null; + try + { + md = MessageDigest.getInstance("MD5"); + } + catch (NoSuchAlgorithmException e) + { + throw new RuntimeException("MD5 not supported although Java compliance requires it"); + } for (byte b : data) { @@ -92,12 +107,22 @@ public class HashedUser implements Principal return _name; } - char[] getPassword() + public char[] getPassword() { return _password; } - void setPassword(char[] password, boolean alreadyHashed) throws UnsupportedEncodingException, NoSuchAlgorithmException + public void setPassword(char[] password) + { + setPassword(password, false); + } + + public void restorePassword(char[] password) + { + setPassword(password, true); + } + + void setPassword(char[] password, boolean alreadyHashed) { if(alreadyHashed){ _password = password; @@ -126,7 +151,7 @@ public class HashedUser implements Principal _encodedPassword = null; } - byte[] getEncodedPassword() throws EncoderException, UnsupportedEncodingException, NoSuchAlgorithmException + public byte[] getEncodedPassword() { if (_encodedPassword == null) { @@ -135,7 +160,7 @@ public class HashedUser implements Principal return _encodedPassword; } - private void encodePassword() throws EncoderException, UnsupportedEncodingException, NoSuchAlgorithmException + private void encodePassword() { byte[] byteArray = new byte[_password.length]; int index = 0; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PasswordPrincipal.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PasswordPrincipal.java new file mode 100644 index 0000000000..8e12d5f0a3 --- /dev/null +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PasswordPrincipal.java @@ -0,0 +1,40 @@ +/* + * + * 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.security.auth.database; + +import java.security.Principal; + +interface PasswordPrincipal extends Principal +{ + char[] getPassword(); + byte[] getEncodedPassword(); + + void setPassword(char[] password); + void restorePassword(char[] password); + + boolean isDeleted(); + + boolean isModified(); + + void saved(); + + void delete(); +} diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PlainPasswordFilePrincipalDatabase.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PlainPasswordFilePrincipalDatabase.java index 7cb34da804..bfd04adb3f 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PlainPasswordFilePrincipalDatabase.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PlainPasswordFilePrincipalDatabase.java @@ -21,29 +21,13 @@ package org.apache.qpid.server.security.auth.database; import org.apache.log4j.Logger; -import org.apache.qpid.server.security.auth.sasl.AuthenticationProviderInitialiser; -import org.apache.qpid.server.security.auth.sasl.UsernamePrincipal; + import org.apache.qpid.server.security.auth.sasl.amqplain.AmqPlainInitialiser; -import org.apache.qpid.server.security.auth.sasl.anonymous.AnonymousInitialiser; import org.apache.qpid.server.security.auth.sasl.crammd5.CRAMMD5Initialiser; import org.apache.qpid.server.security.auth.sasl.plain.PlainInitialiser; -import javax.security.auth.callback.PasswordCallback; import javax.security.auth.login.AccountNotFoundException; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.io.PrintStream; import java.security.Principal; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Random; -import java.util.concurrent.locks.ReentrantLock; -import java.util.regex.Pattern; /** * Represents a user database where the account information is stored in a simple flat file. @@ -52,102 +36,19 @@ import java.util.regex.Pattern; * * where a carriage return separates each username/password pair. Passwords are assumed to be in plain text. */ -public class PlainPasswordFilePrincipalDatabase implements PrincipalDatabase +public class PlainPasswordFilePrincipalDatabase extends AbstractPasswordFilePrincipalDatabase { - public static final String DEFAULT_ENCODING = "utf-8"; - - private static final Logger _logger = Logger.getLogger(PlainPasswordFilePrincipalDatabase.class); - - private File _passwordFile; - - private Pattern _regexp = Pattern.compile(":"); - private Map _saslServers; - - private Map _users = new HashMap(); - private ReentrantLock _userUpdate = new ReentrantLock(); + private final Logger _logger = Logger.getLogger(PlainPasswordFilePrincipalDatabase.class); public PlainPasswordFilePrincipalDatabase() { - _saslServers = new HashMap(); - /** * Create Authenticators for Plain Password file. */ - - // Accept AMQPlain incomming and compare it to the file. - AmqPlainInitialiser amqplain = new AmqPlainInitialiser(); - amqplain.initialise(this); - - - - // Accept AMQPlain incomming and compare it to the file. - AnonymousInitialiser anonymous = new AnonymousInitialiser(); - anonymous.initialise(this); - - - // Accept Plain incomming and compare it to the file. - PlainInitialiser plain = new PlainInitialiser(); - plain.initialise(this); - - // Accept MD5 incomming and Hash file value for comparison - CRAMMD5Initialiser cram = new CRAMMD5Initialiser(); - cram.initialise(this); - - _saslServers.put(amqplain.getMechanismName(), amqplain); - _saslServers.put(plain.getMechanismName(), plain); - _saslServers.put(cram.getMechanismName(), cram); - _saslServers.put(anonymous.getMechanismName(), anonymous); - } - - public void setPasswordFile(String passwordFile) throws IOException - { - File f = new File(passwordFile); - _logger.info("PlainPasswordFile using file " + f.getAbsolutePath()); - _passwordFile = f; - if (!f.exists()) - { - throw new FileNotFoundException("Cannot find password file " + f); - } - if (!f.canRead()) - { - throw new FileNotFoundException("Cannot read password file " + f + - ". Check permissions."); - } - - loadPasswordFile(); + super(new AmqPlainInitialiser(), new PlainInitialiser(), new CRAMMD5Initialiser()); } - /** - * SASL Callback Mechanism - sets the Password in the PasswordCallback based on the value in the PasswordFile - * If you want to change the password for a user, use updatePassword instead. - * - * @param principal The Principal to set the password for - * @param callback The PasswordCallback to call setPassword on - * - * @throws AccountNotFoundException If the Principal cannot be found in this Database - */ - public void setPassword(Principal principal, PasswordCallback callback) throws AccountNotFoundException - { - if (_passwordFile == null) - { - throw new AccountNotFoundException("Unable to locate principal since no password file was specified during initialisation"); - } - if (principal == null) - { - throw new IllegalArgumentException("principal must not be null"); - } - char[] pwd = lookupPassword(principal.getName()); - - if (pwd != null) - { - callback.setPassword(pwd); - } - else - { - throw new AccountNotFoundException("No account found for principal " + principal); - } - } /** * Used to verify that the presented Password is correct. Currently only used by Management Console @@ -173,352 +74,21 @@ public class PlainPasswordFilePrincipalDatabase implements PrincipalDatabase } - /** - * Changes the password for the specified user - * - * @param principal to change the password for - * @param password plaintext password to set the password too - */ - public boolean updatePassword(Principal principal, char[] password) throws AccountNotFoundException + protected PlainUser createUserFromPassword(Principal principal, char[] passwd) { - PlainUser user = _users.get(principal.getName()); - - if (user == null) - { - throw new AccountNotFoundException(principal.getName()); - } - - char[] orig = user.getPassword(); - _userUpdate.lock(); - try - { - user.setPassword(password); - - savePasswordFile(); - - return true; - } - catch (IOException e) - { - _logger.error("Unable to save password file due to '"+e.getMessage() - +"', password change for user '" + principal + "' discarded"); - //revert the password change - user.setPassword(orig); - return false; - } - finally - { - _userUpdate.unlock(); - } + return new PlainUser(principal.getName(), passwd); } - public boolean createPrincipal(Principal principal, char[] password) - { - if (_users.get(principal.getName()) != null) - { - return false; - } - - PlainUser user = new PlainUser(principal.getName(), password); - - try - { - _userUpdate.lock(); - _users.put(user.getName(), user); - - try - { - savePasswordFile(); - return true; - } - catch (IOException e) - { - //remove the use on failure. - _users.remove(user.getName()); - _logger.warn("Unable to create user '" + user.getName()); - return false; - } - } - finally - { - _userUpdate.unlock(); - } - } - public boolean deletePrincipal(Principal principal) throws AccountNotFoundException + @Override + protected PlainUser createUserFromFileData(String[] result) { - PlainUser user = _users.get(principal.getName()); - - if (user == null) - { - throw new AccountNotFoundException(principal.getName()); - } - - try - { - _userUpdate.lock(); - user.delete(); - - try - { - savePasswordFile(); - } - catch (IOException e) - { - _logger.error("Unable to remove user '" + user.getName() + "' from password file."); - return false; - } - - _users.remove(user.getName()); - } - finally - { - _userUpdate.unlock(); - } - - return true; + return new PlainUser(result); } - public Map getMechanisms() - { - return _saslServers; - } - public List getUsers() - { - return new LinkedList(_users.values()); - } - - public Principal getUser(String username) - { - if (_users.containsKey(username)) - { - return new UsernamePrincipal(username); - } - return null; - } - - private boolean compareCharArray(char[] a, char[] b) - { - boolean equal = false; - if (a.length == b.length) - { - equal = true; - int index = 0; - while (equal && index < a.length) - { - equal = a[index] == b[index]; - index++; - } - } - return equal; - } - - - /** - * Looks up the password for a specified user in the password file. Note this code is not secure since it - * creates strings of passwords. It should be modified to create only char arrays which get nulled out. - * - * @param name The principal name to lookup - * - * @return a char[] for use in SASL. - */ - private char[] lookupPassword(String name) - { - PlainUser user = _users.get(name); - if (user == null) - { - return null; - } - else - { - return user.getPassword(); - } - } - - private void loadPasswordFile() throws IOException - { - try - { - _userUpdate.lock(); - _users.clear(); - - BufferedReader reader = null; - try - { - reader = new BufferedReader(new FileReader(_passwordFile)); - String line; - - while ((line = reader.readLine()) != null) - { - String[] result = _regexp.split(line); - if (result == null || result.length < 2 || result[0].startsWith("#")) - { - continue; - } - - PlainUser user = new PlainUser(result); - _logger.info("Created user:" + user); - _users.put(user.getName(), user); - } - } - finally - { - if (reader != null) - { - reader.close(); - } - } - } - finally - { - _userUpdate.unlock(); - } - } - - private void savePasswordFile() throws IOException - { - try - { - _userUpdate.lock(); - - BufferedReader reader = null; - PrintStream writer = null; - - final File tmp = createTempFileOnSameFilesystem(_passwordFile); - - try - { - writer = new PrintStream(tmp); - reader = new BufferedReader(new FileReader(_passwordFile)); - String line; - - while ((line = reader.readLine()) != null) - { - String[] result = _regexp.split(line); - if (result == null || result.length < 2 || result[0].startsWith("#")) - { - writer.write(line.getBytes(DEFAULT_ENCODING)); - writer.println(); - continue; - } - - PlainUser user = _users.get(result[0]); - - if (user == null) - { - writer.write(line.getBytes(DEFAULT_ENCODING)); - writer.println(); - } - else if (!user.isDeleted()) - { - if (!user.isModified()) - { - writer.write(line.getBytes(DEFAULT_ENCODING)); - writer.println(); - } - else - { - byte[] password = user.getPasswordBytes(); - - writer.write((user.getName() + ":").getBytes(DEFAULT_ENCODING)); - writer.write(password); - writer.println(); - - user.saved(); - } - } - } - - for (PlainUser user : _users.values()) - { - if (user.isModified()) - { - byte[] password; - password = user.getPasswordBytes(); - writer.write((user.getName() + ":").getBytes(DEFAULT_ENCODING)); - writer.write(password); - writer.println(); - user.saved(); - } - } - } - catch(IOException e) - { - _logger.error("Unable to create the new password file: " + e); - throw new IOException("Unable to create the new password file" + e); - } - finally - { - if (writer != null) - { - writer.close(); - } - if (reader != null) - { - reader.close(); - } - } - - swapTempFileToLive(_passwordFile, tmp); - - } - finally - { - _userUpdate.unlock(); - } - } - - private void swapTempFileToLive(final File live, final File temp) throws IOException - { - // Remove any existing ".old" file - final File old = new File(live.getAbsoluteFile() + ".old"); - if (old.exists()) - { - old.delete(); - } - - // Create an new ".old" file - if(!live.renameTo(old)) - { - //unable to rename the existing file to the backup name - _logger.error("Could not backup the existing password file"); - throw new IOException("Could not backup the existing password file"); - } - - // Move temp file to be the new "live" file - if(!temp.renameTo(live)) - { - //failed to rename the new file to the required filename - if(!old.renameTo(live)) - { - //unable to return the backup to required filename - _logger.error("Could not rename the new password file into place, and unable to restore original file"); - throw new IOException("Could not rename the new password file into place, and unable to restore original file"); - } - - _logger.error("Could not rename the new password file into place"); - throw new IOException("Could not rename the new password file into place"); - } - } - - private File createTempFileOnSameFilesystem(final File liveFile) - { - File tmp; - final Random r = new Random(); - - do - { - tmp = new File(liveFile.getPath() + r.nextInt() + ".tmp"); - } - while(tmp.exists()); - - tmp.deleteOnExit(); - return tmp; - } - - public void reload() throws IOException + protected Logger getLogger() { - loadPasswordFile(); + return _logger; } } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PlainUser.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PlainUser.java index 46a78a55aa..bf9bfc6c99 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PlainUser.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PlainUser.java @@ -20,11 +20,7 @@ */ package org.apache.qpid.server.security.auth.database; -import org.apache.log4j.Logger; - -import java.security.Principal; - -public class PlainUser implements Principal +public class PlainUser implements PasswordPrincipal { private String _name; private char[] _password; @@ -61,12 +57,12 @@ public class PlainUser implements Principal return _name; } - char[] getPassword() + public char[] getPassword() { return _password; } - byte[] getPasswordBytes() + public byte[] getEncodedPassword() { byte[] byteArray = new byte[_password.length]; int index = 0; @@ -77,7 +73,14 @@ public class PlainUser implements Principal return byteArray; } - void setPassword(char[] password) + + + public void restorePassword(char[] password) + { + setPassword(password); + } + + public void setPassword(char[] password) { _password = password; _modified = true; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PrincipalDatabase.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PrincipalDatabase.java index ef37e043a6..67f4b7344a 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PrincipalDatabase.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PrincipalDatabase.java @@ -22,14 +22,12 @@ package org.apache.qpid.server.security.auth.database; import org.apache.qpid.server.security.auth.sasl.AuthenticationProviderInitialiser; +import javax.security.auth.callback.PasswordCallback; +import javax.security.auth.login.AccountNotFoundException; import java.io.IOException; -import java.io.UnsupportedEncodingException; import java.security.Principal; -import java.util.Map; import java.util.List; - -import javax.security.auth.callback.PasswordCallback; -import javax.security.auth.login.AccountNotFoundException; +import java.util.Map; /** Represents a "user database" which is really a way of storing principals (i.e. usernames) and passwords. */ public interface PrincipalDatabase diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PropertiesPrincipalDatabase.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PropertiesPrincipalDatabase.java index ff8851306f..4203cb0e07 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PropertiesPrincipalDatabase.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/PropertiesPrincipalDatabase.java @@ -27,14 +27,14 @@ import org.apache.qpid.server.security.auth.sasl.plain.PlainInitialiser; import javax.security.auth.callback.PasswordCallback; import javax.security.auth.login.AccountNotFoundException; -import java.util.Properties; -import java.util.Map; -import java.util.HashMap; -import java.util.List; -import java.util.LinkedList; -import java.security.Principal; import java.io.IOException; import java.io.UnsupportedEncodingException; +import java.security.Principal; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Properties; public class PropertiesPrincipalDatabase implements PrincipalDatabase { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/management/AMQUserManagementMBean.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/management/AMQUserManagementMBean.java index 208130379e..1314a5d6a6 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/management/AMQUserManagementMBean.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/management/AMQUserManagementMBean.java @@ -20,9 +20,14 @@ */ package org.apache.qpid.server.security.auth.management; -import java.io.IOException; -import java.security.Principal; -import java.util.List; +import org.apache.log4j.Logger; + +import org.apache.qpid.management.common.mbeans.UserManagement; +import org.apache.qpid.management.common.mbeans.annotations.MBeanDescription; +import org.apache.qpid.management.common.mbeans.annotations.MBeanOperation; +import org.apache.qpid.server.management.AMQManagedObject; +import org.apache.qpid.server.security.auth.database.PrincipalDatabase; +import org.apache.qpid.server.security.auth.sasl.UsernamePrincipal; import javax.management.JMException; import javax.management.openmbean.CompositeData; @@ -35,14 +40,9 @@ import javax.management.openmbean.TabularData; import javax.management.openmbean.TabularDataSupport; import javax.management.openmbean.TabularType; import javax.security.auth.login.AccountNotFoundException; - -import org.apache.log4j.Logger; -import org.apache.qpid.management.common.mbeans.UserManagement; -import org.apache.qpid.management.common.mbeans.annotations.MBeanDescription; -import org.apache.qpid.management.common.mbeans.annotations.MBeanOperation; -import org.apache.qpid.server.management.AMQManagedObject; -import org.apache.qpid.server.security.auth.database.PrincipalDatabase; -import org.apache.qpid.server.security.auth.sasl.UsernamePrincipal; +import java.io.IOException; +import java.security.Principal; +import java.util.List; /** MBean class for AMQUserManagementMBean. It implements all the management features exposed for managing users. */ @MBeanDescription("User Management Interface") diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/manager/AuthenticationManager.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/manager/AuthenticationManager.java index 82eb7d3621..03cc12d06c 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/manager/AuthenticationManager.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/manager/AuthenticationManager.java @@ -20,21 +20,20 @@ */ package org.apache.qpid.server.security.auth.manager; -import javax.security.auth.Subject; -import javax.security.sasl.SaslException; -import javax.security.sasl.SaslServer; - import org.apache.qpid.amqp_1_0.transport.CallbackHanderSource; import org.apache.qpid.common.Closeable; import org.apache.qpid.server.plugins.Plugin; import org.apache.qpid.server.security.auth.AuthenticationResult; +import javax.security.sasl.SaslException; +import javax.security.sasl.SaslServer; + /** * Implementations of the AuthenticationManager are responsible for determining * the authenticity of a user's credentials. * * If the authentication is successful, the manager is responsible for producing a populated - * {@link Subject} containing the user's identity and zero or more principals representing + * {@link javax.security.auth.Subject} containing the user's identity and zero or more principals representing * groups to which the user belongs. *

* The {@link #initialise()} method is responsible for registering SASL mechanisms required by diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/manager/PrincipalDatabaseAuthenticationManager.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/manager/PrincipalDatabaseAuthenticationManager.java index 978ad2b1f3..b5d70d9200 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/manager/PrincipalDatabaseAuthenticationManager.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/manager/PrincipalDatabaseAuthenticationManager.java @@ -20,29 +20,10 @@ */ package org.apache.qpid.server.security.auth.manager; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.security.Security; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.TreeMap; - -import javax.security.auth.Subject; -import javax.security.auth.callback.CallbackHandler; -import javax.security.auth.login.AccountNotFoundException; -import javax.security.sasl.Sasl; -import javax.security.sasl.SaslException; -import javax.security.sasl.SaslServer; -import javax.security.sasl.SaslServerFactory; - import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.ConfigurationException; import org.apache.log4j.Logger; + import org.apache.qpid.configuration.PropertyException; import org.apache.qpid.configuration.PropertyUtils; import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin; @@ -55,6 +36,25 @@ import org.apache.qpid.server.security.auth.sasl.AuthenticationProviderInitialis import org.apache.qpid.server.security.auth.sasl.JCAProvider; import org.apache.qpid.server.security.auth.sasl.UsernamePrincipal; +import javax.security.auth.Subject; +import javax.security.auth.callback.CallbackHandler; +import javax.security.auth.login.AccountNotFoundException; +import javax.security.sasl.Sasl; +import javax.security.sasl.SaslException; +import javax.security.sasl.SaslServer; +import javax.security.sasl.SaslServerFactory; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.security.Security; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.TreeMap; + /** * Concrete implementation of the AuthenticationManager that determines if supplied @@ -95,9 +95,9 @@ public class PrincipalDatabaseAuthenticationManager implements AuthenticationMan */ private final Map> _serverCreationProperties = new HashMap>(); - protected PrincipalDatabase _principalDatabase = null; + private PrincipalDatabase _principalDatabase = null; - protected AMQUserManagementMBean _mbean = null; + private AMQUserManagementMBean _mbean = null; public static final AuthenticationManagerPluginFactory FACTORY = new AuthenticationManagerPluginFactory() { @@ -160,13 +160,13 @@ public class PrincipalDatabaseAuthenticationManager implements AuthenticationMan public String getPrincipalDatabaseClass() { - return _configuration.getString("principal-database.class"); + return getConfig().getString("principal-database.class"); } public Map getPdClassAttributeMap() throws ConfigurationException { - final List argumentNames = _configuration.getList("principal-database.attributes.attribute.name"); - final List argumentValues = _configuration.getList("principal-database.attributes.attribute.value"); + final List argumentNames = getConfig().getList("principal-database.attributes.attribute.name"); + final List argumentValues = getConfig().getList("principal-database.attributes.attribute.value"); final Map attributes = new HashMap(argumentNames.size()); for (int i = 0; i < argumentNames.size(); i++) diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/rmi/RMIPasswordAuthenticator.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/rmi/RMIPasswordAuthenticator.java index b7985ad972..e27fd99f90 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/rmi/RMIPasswordAuthenticator.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/rmi/RMIPasswordAuthenticator.java @@ -20,14 +20,14 @@ */ package org.apache.qpid.server.security.auth.rmi; -import javax.management.remote.JMXAuthenticator; -import javax.management.remote.JMXPrincipal; -import javax.security.auth.Subject; - import org.apache.qpid.server.security.auth.AuthenticationResult; import org.apache.qpid.server.security.auth.AuthenticationResult.AuthenticationStatus; import org.apache.qpid.server.security.auth.manager.AuthenticationManager; +import javax.management.remote.JMXAuthenticator; +import javax.management.remote.JMXPrincipal; +import javax.security.auth.Subject; + public class RMIPasswordAuthenticator implements JMXAuthenticator { static final String UNABLE_TO_LOOKUP = "The broker was unable to lookup the user details"; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/AuthenticationProviderInitialiser.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/AuthenticationProviderInitialiser.java index bc5d8a4f2b..c227aa14e8 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/AuthenticationProviderInitialiser.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/AuthenticationProviderInitialiser.java @@ -20,10 +20,9 @@ */ package org.apache.qpid.server.security.auth.sasl; -import java.util.Map; - import javax.security.auth.callback.CallbackHandler; import javax.security.sasl.SaslServerFactory; +import java.util.Map; public interface AuthenticationProviderInitialiser { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/JCAProvider.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/JCAProvider.java index d6f6c714e2..8711e1b385 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/JCAProvider.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/JCAProvider.java @@ -20,11 +20,10 @@ */ package org.apache.qpid.server.security.auth.sasl; +import javax.security.sasl.SaslServerFactory; import java.security.Provider; import java.util.Map; -import javax.security.sasl.SaslServerFactory; - public class JCAProvider extends Provider { public JCAProvider(String name, Map> providerMap) diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/UsernamePasswordInitialiser.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/UsernamePasswordInitialiser.java index 5c13e03886..f4e8f800c6 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/UsernamePasswordInitialiser.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/UsernamePasswordInitialiser.java @@ -20,9 +20,10 @@ */ package org.apache.qpid.server.security.auth.sasl; -import java.io.IOException; -import java.security.Principal; -import java.util.Map; +import org.apache.commons.configuration.Configuration; +import org.apache.log4j.Logger; + +import org.apache.qpid.server.security.auth.database.PrincipalDatabase; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; @@ -31,14 +32,9 @@ import javax.security.auth.callback.PasswordCallback; import javax.security.auth.callback.UnsupportedCallbackException; import javax.security.auth.login.AccountNotFoundException; import javax.security.sasl.AuthorizeCallback; - -import org.apache.commons.configuration.Configuration; - -import org.apache.log4j.Logger; - -import org.apache.qpid.server.security.auth.database.PrincipalDatabase; -import org.apache.qpid.server.security.auth.sasl.AuthenticationProviderInitialiser; -import org.apache.qpid.server.security.auth.sasl.UsernamePrincipal; +import java.io.IOException; +import java.security.Principal; +import java.util.Map; public abstract class UsernamePasswordInitialiser implements AuthenticationProviderInitialiser { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/UsernamePrincipal.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/UsernamePrincipal.java index b4ee13fe6b..9e7db94216 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/UsernamePrincipal.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/UsernamePrincipal.java @@ -20,11 +20,10 @@ */ package org.apache.qpid.server.security.auth.sasl; +import javax.security.auth.Subject; import java.security.Principal; import java.util.Set; -import javax.security.auth.Subject; - /** A principal that is just a wrapper for a simple username. */ public class UsernamePrincipal implements Principal { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/amqplain/AmqPlainInitialiser.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/amqplain/AmqPlainInitialiser.java index 7acc6322d1..860307215f 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/amqplain/AmqPlainInitialiser.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/amqplain/AmqPlainInitialiser.java @@ -20,10 +20,10 @@ */ package org.apache.qpid.server.security.auth.sasl.amqplain; -import javax.security.sasl.SaslServerFactory; - import org.apache.qpid.server.security.auth.sasl.UsernamePasswordInitialiser; +import javax.security.sasl.SaslServerFactory; + public class AmqPlainInitialiser extends UsernamePasswordInitialiser { public String getMechanismName() diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/amqplain/AmqPlainSaslServer.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/amqplain/AmqPlainSaslServer.java index dee40e7069..eecc704011 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/amqplain/AmqPlainSaslServer.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/amqplain/AmqPlainSaslServer.java @@ -20,9 +20,9 @@ */ package org.apache.qpid.server.security.auth.sasl.amqplain; -import java.io.ByteArrayInputStream; -import java.io.DataInputStream; -import java.io.IOException; +import org.apache.qpid.framing.AMQFrameDecodingException; +import org.apache.qpid.framing.FieldTable; +import org.apache.qpid.framing.FieldTableFactory; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; @@ -32,10 +32,9 @@ import javax.security.auth.callback.UnsupportedCallbackException; import javax.security.sasl.AuthorizeCallback; import javax.security.sasl.SaslException; import javax.security.sasl.SaslServer; - -import org.apache.qpid.framing.AMQFrameDecodingException; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.framing.FieldTableFactory; +import java.io.ByteArrayInputStream; +import java.io.DataInputStream; +import java.io.IOException; public class AmqPlainSaslServer implements SaslServer { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/amqplain/AmqPlainSaslServerFactory.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/amqplain/AmqPlainSaslServerFactory.java index 17d123eb0d..3a73f577fe 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/amqplain/AmqPlainSaslServerFactory.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/amqplain/AmqPlainSaslServerFactory.java @@ -20,13 +20,12 @@ */ package org.apache.qpid.server.security.auth.sasl.amqplain; -import java.util.Map; - import javax.security.auth.callback.CallbackHandler; import javax.security.sasl.Sasl; import javax.security.sasl.SaslException; import javax.security.sasl.SaslServer; import javax.security.sasl.SaslServerFactory; +import java.util.Map; public class AmqPlainSaslServerFactory implements SaslServerFactory { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/anonymous/AnonymousInitialiser.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/anonymous/AnonymousInitialiser.java index e35e999766..83369a84c7 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/anonymous/AnonymousInitialiser.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/anonymous/AnonymousInitialiser.java @@ -20,53 +20,17 @@ */ package org.apache.qpid.server.security.auth.sasl.anonymous; -import javax.security.auth.callback.Callback; -import javax.security.auth.callback.CallbackHandler; -import javax.security.auth.callback.UnsupportedCallbackException; -import javax.security.sasl.SaslServerFactory; - -import org.apache.commons.configuration.Configuration; -import org.apache.qpid.server.security.auth.database.PrincipalDatabase; -import org.apache.qpid.server.security.auth.sasl.AuthenticationProviderInitialiser; import org.apache.qpid.server.security.auth.sasl.UsernamePasswordInitialiser; -import java.io.IOException; -import java.util.Map; +import javax.security.sasl.SaslServerFactory; -public class AnonymousInitialiser implements AuthenticationProviderInitialiser +public class AnonymousInitialiser extends UsernamePasswordInitialiser { public String getMechanismName() { return "ANONYMOUS"; } - public void initialise(String baseConfigPath, Configuration configuration, Map principalDatabases) throws Exception - { - } - - public void initialise(PrincipalDatabase db) - { - } - - public CallbackHandler getCallbackHandler() - { - return new CallbackHandler() - { - - public Callback[] _callbacks; - - public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException - { - _callbacks =callbacks; - } - }; - } - - public Map getProperties() - { - return null; - } - public Class getServerFactoryClassForJCARegistration() { return AnonymousSaslServerFactory.class; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/anonymous/AnonymousSaslServerFactory.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/anonymous/AnonymousSaslServerFactory.java index de695032ab..4650234972 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/anonymous/AnonymousSaslServerFactory.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/anonymous/AnonymousSaslServerFactory.java @@ -20,15 +20,12 @@ */ package org.apache.qpid.server.security.auth.sasl.anonymous; -import org.apache.qpid.server.security.auth.sasl.amqplain.AmqPlainSaslServer; - -import java.util.Map; - import javax.security.auth.callback.CallbackHandler; import javax.security.sasl.Sasl; import javax.security.sasl.SaslException; import javax.security.sasl.SaslServer; import javax.security.sasl.SaslServerFactory; +import java.util.Map; public class AnonymousSaslServerFactory implements SaslServerFactory { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HashedInitialiser.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HashedInitialiser.java index 97f9a4e91a..842215c3eb 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HashedInitialiser.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HashedInitialiser.java @@ -20,8 +20,8 @@ */ package org.apache.qpid.server.security.auth.sasl.crammd5; -import org.apache.qpid.server.security.auth.sasl.UsernamePasswordInitialiser; import org.apache.qpid.server.security.auth.database.PrincipalDatabase; +import org.apache.qpid.server.security.auth.sasl.UsernamePasswordInitialiser; import javax.security.sasl.SaslServerFactory; import java.util.Map; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HashedSaslServer.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HashedSaslServer.java index f6cab084ea..a2d9fa5e3e 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HashedSaslServer.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HashedSaslServer.java @@ -20,11 +20,11 @@ */ package org.apache.qpid.server.security.auth.sasl.crammd5; -import javax.security.sasl.SaslServer; -import javax.security.sasl.SaslException; +import javax.security.auth.callback.CallbackHandler; import javax.security.sasl.Sasl; +import javax.security.sasl.SaslException; +import javax.security.sasl.SaslServer; import javax.security.sasl.SaslServerFactory; -import javax.security.auth.callback.CallbackHandler; import java.util.Enumeration; import java.util.Map; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HashedServerFactory.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HashedServerFactory.java index 5298b5cc63..4e82940439 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HashedServerFactory.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HashedServerFactory.java @@ -20,13 +20,12 @@ */ package org.apache.qpid.server.security.auth.sasl.crammd5; -import java.util.Map; - import javax.security.auth.callback.CallbackHandler; import javax.security.sasl.Sasl; import javax.security.sasl.SaslException; import javax.security.sasl.SaslServer; import javax.security.sasl.SaslServerFactory; +import java.util.Map; public class CRAMMD5HashedServerFactory implements SaslServerFactory { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HexInitialiser.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HexInitialiser.java index 139818735f..478f195530 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HexInitialiser.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HexInitialiser.java @@ -21,16 +21,16 @@ package org.apache.qpid.server.security.auth.sasl.crammd5; import org.apache.qpid.server.security.auth.database.PrincipalDatabase; -import org.apache.qpid.server.security.auth.sasl.UsernamePasswordInitialiser; import org.apache.qpid.server.security.auth.sasl.AuthenticationProviderInitialiser; +import org.apache.qpid.server.security.auth.sasl.UsernamePasswordInitialiser; -import javax.security.sasl.SaslServerFactory; import javax.security.auth.callback.PasswordCallback; import javax.security.auth.login.AccountNotFoundException; -import java.util.Map; -import java.util.List; -import java.security.Principal; +import javax.security.sasl.SaslServerFactory; import java.io.IOException; +import java.security.Principal; +import java.util.List; +import java.util.Map; public class CRAMMD5HexInitialiser extends UsernamePasswordInitialiser { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HexSaslServer.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HexSaslServer.java index 192ff74bff..e19baaa7c6 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HexSaslServer.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HexSaslServer.java @@ -20,11 +20,11 @@ */ package org.apache.qpid.server.security.auth.sasl.crammd5; -import javax.security.sasl.SaslServer; -import javax.security.sasl.SaslException; +import javax.security.auth.callback.CallbackHandler; import javax.security.sasl.Sasl; +import javax.security.sasl.SaslException; +import javax.security.sasl.SaslServer; import javax.security.sasl.SaslServerFactory; -import javax.security.auth.callback.CallbackHandler; import java.util.Enumeration; import java.util.Map; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HexServerFactory.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HexServerFactory.java index ce0e19abf9..06c9108a73 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HexServerFactory.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5HexServerFactory.java @@ -20,13 +20,12 @@ */ package org.apache.qpid.server.security.auth.sasl.crammd5; -import java.util.Map; - import javax.security.auth.callback.CallbackHandler; import javax.security.sasl.Sasl; import javax.security.sasl.SaslException; import javax.security.sasl.SaslServer; import javax.security.sasl.SaslServerFactory; +import java.util.Map; public class CRAMMD5HexServerFactory implements SaslServerFactory { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5Initialiser.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5Initialiser.java index 264832888d..83e33d5491 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5Initialiser.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/crammd5/CRAMMD5Initialiser.java @@ -20,8 +20,8 @@ */ package org.apache.qpid.server.security.auth.sasl.crammd5; -import org.apache.qpid.server.security.auth.sasl.UsernamePasswordInitialiser; import org.apache.qpid.server.security.auth.database.PrincipalDatabase; +import org.apache.qpid.server.security.auth.sasl.UsernamePasswordInitialiser; import javax.security.sasl.SaslServerFactory; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainInitialiser.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainInitialiser.java index 1d16cd8755..67676d363e 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainInitialiser.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainInitialiser.java @@ -20,10 +20,10 @@ */ package org.apache.qpid.server.security.auth.sasl.plain; -import javax.security.sasl.SaslServerFactory; - import org.apache.qpid.server.security.auth.sasl.UsernamePasswordInitialiser; +import javax.security.sasl.SaslServerFactory; + public class PlainInitialiser extends UsernamePasswordInitialiser { public String getMechanismName() diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainPasswordCallback.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainPasswordCallback.java index 7230e8ee53..0ea2f3c92e 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainPasswordCallback.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainPasswordCallback.java @@ -20,9 +20,8 @@ */ package org.apache.qpid.server.security.auth.sasl.plain; -import java.util.Arrays; - import javax.security.auth.callback.PasswordCallback; +import java.util.Arrays; /** * Custom PasswordCallback for use during the PLAIN authentication process. diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainSaslServer.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainSaslServer.java index 847a3a34ce..a811806c00 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainSaslServer.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainSaslServer.java @@ -20,16 +20,14 @@ */ package org.apache.qpid.server.security.auth.sasl.plain; -import java.io.IOException; - import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.NameCallback; -import javax.security.auth.callback.PasswordCallback; import javax.security.auth.callback.UnsupportedCallbackException; import javax.security.sasl.AuthorizeCallback; import javax.security.sasl.SaslException; import javax.security.sasl.SaslServer; +import java.io.IOException; public class PlainSaslServer implements SaslServer { @@ -53,57 +51,65 @@ public class PlainSaslServer implements SaslServer public byte[] evaluateResponse(byte[] response) throws SaslException { - try + int authzidNullPosition = findNullPosition(response, 0); + if (authzidNullPosition < 0) { - int authzidNullPosition = findNullPosition(response, 0); - if (authzidNullPosition < 0) - { - throw new SaslException("Invalid PLAIN encoding, authzid null terminator not found"); - } - int authcidNullPosition = findNullPosition(response, authzidNullPosition + 1); - if (authcidNullPosition < 0) - { - throw new SaslException("Invalid PLAIN encoding, authcid null terminator not found"); - } + throw new SaslException("Invalid PLAIN encoding, authzid null terminator not found"); + } + int authcidNullPosition = findNullPosition(response, authzidNullPosition + 1); + if (authcidNullPosition < 0) + { + throw new SaslException("Invalid PLAIN encoding, authcid null terminator not found"); + } + + PlainPasswordCallback passwordCb; + AuthorizeCallback authzCb; + try + { // we do not currently support authcid in any meaningful way - // String authcid = new String(response, 0, authzidNullPosition, "utf8"); String authzid = new String(response, authzidNullPosition + 1, authcidNullPosition - authzidNullPosition - 1, "utf8"); // TODO: should not get pwd as a String but as a char array... int passwordLen = response.length - authcidNullPosition - 1; String pwd = new String(response, authcidNullPosition + 1, passwordLen, "utf8"); - + // we do not care about the prompt but it throws if null NameCallback nameCb = new NameCallback("prompt", authzid); - PlainPasswordCallback passwordCb = new PlainPasswordCallback("prompt", false, pwd); - AuthorizeCallback authzCb = new AuthorizeCallback(authzid, authzid); + passwordCb = new PlainPasswordCallback("prompt", false, pwd); + authzCb = new AuthorizeCallback(authzid, authzid); Callback[] callbacks = new Callback[]{nameCb, passwordCb, authzCb}; _cbh.handle(callbacks); - if (passwordCb.isAuthenticated()) - { - _complete = true; - } - if (authzCb.isAuthorized() && _complete) - { - _authorizationId = authzCb.getAuthenticationID(); - return null; - } - else - { - throw new SaslException("Authentication failed"); - } } catch (IOException e) { + if(e instanceof SaslException) + { + throw (SaslException) e; + } throw new SaslException("Error processing data: " + e, e); } catch (UnsupportedCallbackException e) { throw new SaslException("Unable to obtain data from callback handler: " + e, e); } + + if (passwordCb.isAuthenticated()) + { + _complete = true; + } + + if (authzCb.isAuthorized() && _complete) + { + _authorizationId = authzCb.getAuthenticationID(); + return null; + } + else + { + throw new SaslException("Authentication failed"); + } } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainSaslServerFactory.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainSaslServerFactory.java index 3144bfbce6..445e5ef812 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainSaslServerFactory.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainSaslServerFactory.java @@ -20,13 +20,12 @@ */ package org.apache.qpid.server.security.auth.sasl.plain; -import java.util.Map; - import javax.security.auth.callback.CallbackHandler; import javax.security.sasl.Sasl; import javax.security.sasl.SaslException; import javax.security.sasl.SaslServer; import javax.security.sasl.SaslServerFactory; +import java.util.Map; public class PlainSaslServerFactory implements SaslServerFactory { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/signal/SignalHandlerTask.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/signal/SignalHandlerTask.java index 4e3fae1dbd..bdcfd86f82 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/signal/SignalHandlerTask.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/signal/SignalHandlerTask.java @@ -20,13 +20,13 @@ */ package org.apache.qpid.server.signal; +import org.apache.log4j.Logger; + import java.lang.reflect.Constructor; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; -import org.apache.log4j.Logger; - public abstract class SignalHandlerTask { private static final Logger LOGGER = Logger.getLogger(SignalHandlerTask.class); diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/state/AMQStateManager.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/state/AMQStateManager.java index 33aebffcfb..f97b77a4fe 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/state/AMQStateManager.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/state/AMQStateManager.java @@ -20,51 +20,23 @@ */ package org.apache.qpid.server.state; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.CopyOnWriteArraySet; - import org.apache.log4j.Logger; import org.apache.qpid.AMQException; -import org.apache.qpid.AMQConnectionException; -import org.apache.qpid.framing.*; +import org.apache.qpid.framing.AMQMethodBody; +import org.apache.qpid.framing.ChannelCloseBody; +import org.apache.qpid.framing.ChannelCloseOkBody; +import org.apache.qpid.framing.ChannelOpenBody; +import org.apache.qpid.framing.MethodDispatcher; +import org.apache.qpid.protocol.AMQConstant; import org.apache.qpid.protocol.AMQMethodEvent; import org.apache.qpid.protocol.AMQMethodListener; -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.server.handler.BasicAckMethodHandler; -import org.apache.qpid.server.handler.BasicCancelMethodHandler; -import org.apache.qpid.server.handler.BasicConsumeMethodHandler; -import org.apache.qpid.server.handler.BasicGetMethodHandler; -import org.apache.qpid.server.handler.BasicPublishMethodHandler; -import org.apache.qpid.server.handler.BasicQosHandler; -import org.apache.qpid.server.handler.BasicRecoverMethodHandler; -import org.apache.qpid.server.handler.BasicRejectMethodHandler; -import org.apache.qpid.server.handler.ChannelCloseHandler; -import org.apache.qpid.server.handler.ChannelCloseOkHandler; -import org.apache.qpid.server.handler.ChannelFlowHandler; -import org.apache.qpid.server.handler.ChannelOpenHandler; -import org.apache.qpid.server.handler.ConnectionCloseMethodHandler; -import org.apache.qpid.server.handler.ConnectionCloseOkMethodHandler; -import org.apache.qpid.server.handler.ConnectionOpenMethodHandler; -import org.apache.qpid.server.handler.ConnectionSecureOkMethodHandler; -import org.apache.qpid.server.handler.ConnectionStartOkMethodHandler; -import org.apache.qpid.server.handler.ConnectionTuneOkMethodHandler; -import org.apache.qpid.server.handler.ExchangeBoundHandler; -import org.apache.qpid.server.handler.ExchangeDeclareHandler; -import org.apache.qpid.server.handler.ExchangeDeleteHandler; -import org.apache.qpid.server.handler.QueueBindHandler; -import org.apache.qpid.server.handler.QueueDeclareHandler; -import org.apache.qpid.server.handler.QueueDeleteHandler; -import org.apache.qpid.server.handler.QueuePurgeHandler; -import org.apache.qpid.server.handler.TxCommitHandler; -import org.apache.qpid.server.handler.TxRollbackHandler; -import org.apache.qpid.server.handler.TxSelectHandler; import org.apache.qpid.server.protocol.AMQProtocolSession; import org.apache.qpid.server.security.SecurityManager; import org.apache.qpid.server.virtualhost.VirtualHostRegistry; +import java.util.concurrent.CopyOnWriteArraySet; + /** * The state manager is responsible for managing the state of the protocol session.

For each AMQProtocolHandler * there is a separate state manager. @@ -78,16 +50,6 @@ public class AMQStateManager implements AMQMethodListener /** The current state */ private AMQState _currentState; - /** - * Maps from an AMQState instance to a Map from Class to StateTransitionHandler. The class must be a subclass of - * AMQFrame. - */ -/* private final EnumMap, StateAwareMethodListener>> _state2HandlersMap = - new EnumMap, StateAwareMethodListener>>( - AMQState.class); - */ - - private CopyOnWriteArraySet _stateListeners = new CopyOnWriteArraySet(); public AMQStateManager(VirtualHostRegistry virtualHostRegistry, AMQProtocolSession protocolSession) @@ -99,64 +61,6 @@ public class AMQStateManager implements AMQMethodListener } - /* - protected void registerListeners() - { - Map, StateAwareMethodListener> frame2handlerMap; - - frame2handlerMap = new HashMap, StateAwareMethodListener>(); - _state2HandlersMap.put(AMQState.CONNECTION_NOT_STARTED, frame2handlerMap); - - frame2handlerMap = new HashMap, StateAwareMethodListener>(); - _state2HandlersMap.put(AMQState.CONNECTION_NOT_AUTH, frame2handlerMap); - - frame2handlerMap = new HashMap, StateAwareMethodListener>(); - _state2HandlersMap.put(AMQState.CONNECTION_NOT_TUNED, frame2handlerMap); - - frame2handlerMap = new HashMap, StateAwareMethodListener>(); - frame2handlerMap.put(ConnectionOpenBody.class, ConnectionOpenMethodHandler.getInstance()); - _state2HandlersMap.put(AMQState.CONNECTION_NOT_OPENED, frame2handlerMap); - - // - // ConnectionOpen handlers - // - frame2handlerMap = new HashMap, StateAwareMethodListener>(); - ChannelOpenHandler.getInstance(); - ChannelCloseHandler.getInstance(); - ChannelCloseOkHandler.getInstance(); - ConnectionCloseMethodHandler.getInstance(); - ConnectionCloseOkMethodHandler.getInstance(); - ConnectionTuneOkMethodHandler.getInstance(); - ConnectionSecureOkMethodHandler.getInstance(); - ConnectionStartOkMethodHandler.getInstance(); - ExchangeDeclareHandler.getInstance(); - ExchangeDeleteHandler.getInstance(); - ExchangeBoundHandler.getInstance(); - BasicAckMethodHandler.getInstance(); - BasicRecoverMethodHandler.getInstance(); - BasicConsumeMethodHandler.getInstance(); - BasicGetMethodHandler.getInstance(); - BasicCancelMethodHandler.getInstance(); - BasicPublishMethodHandler.getInstance(); - BasicQosHandler.getInstance(); - QueueBindHandler.getInstance(); - QueueDeclareHandler.getInstance(); - QueueDeleteHandler.getInstance(); - QueuePurgeHandler.getInstance(); - ChannelFlowHandler.getInstance(); - TxSelectHandler.getInstance(); - TxCommitHandler.getInstance(); - TxRollbackHandler.getInstance(); - BasicRejectMethodHandler.getInstance(); - - _state2HandlersMap.put(AMQState.CONNECTION_OPEN, frame2handlerMap); - - frame2handlerMap = new HashMap, StateAwareMethodListener>(); - - _state2HandlersMap.put(AMQState.CONNECTION_CLOSING, frame2handlerMap); - - } */ - public AMQState getCurrentState() { return _currentState; @@ -217,30 +121,6 @@ public class AMQStateManager implements AMQMethodListener } } -/* - protected StateAwareMethodListener findStateTransitionHandler(AMQState currentState, - B frame) - // throws IllegalStateTransitionException - { - final Map, StateAwareMethodListener> classToHandlerMap = - _state2HandlersMap.get(currentState); - - final StateAwareMethodListener handler = - (classToHandlerMap == null) ? null : (StateAwareMethodListener) classToHandlerMap.get(frame.getClass()); - - if (handler == null) - { - _logger.debug("No state transition handler defined for receiving frame " + frame); - - return null; - } - else - { - return handler; - } - } -*/ - public void addStateListener(StateListener listener) { _logger.debug("Adding state listener"); diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/state/StateAwareMethodListener.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/state/StateAwareMethodListener.java index 3c11bb8a9c..b543728f3b 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/state/StateAwareMethodListener.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/state/StateAwareMethodListener.java @@ -22,7 +22,6 @@ package org.apache.qpid.server.state; import org.apache.qpid.AMQException; import org.apache.qpid.framing.AMQMethodBody; -import org.apache.qpid.protocol.AMQMethodEvent; /** * A frame listener that is informed of the protocol state when invoked and has diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/stats/StatisticsCounter.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/stats/StatisticsCounter.java index b732121180..2bd17cfa2f 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/stats/StatisticsCounter.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/stats/StatisticsCounter.java @@ -18,12 +18,12 @@ */ package org.apache.qpid.server.stats; -import java.util.Date; -import java.util.concurrent.atomic.AtomicLong; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.Date; +import java.util.concurrent.atomic.AtomicLong; + /** * This class collects statistics and counts the total, rate per second and * peak rate per second values for the events that are registered with it. diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/store/AbstractMessageStore.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/store/AbstractMessageStore.java index b9adaeacdf..fc5d2a4e42 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/store/AbstractMessageStore.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/store/AbstractMessageStore.java @@ -20,15 +20,15 @@ */ package org.apache.qpid.server.store; -import org.apache.qpid.server.virtualhost.VirtualHost; +import org.apache.qpid.server.logging.LogSubject; import org.apache.qpid.server.logging.actors.CurrentActor; import org.apache.qpid.server.logging.messages.MessageStoreMessages; import org.apache.qpid.server.logging.subjects.MessageStoreLogSubject; -import org.apache.qpid.server.logging.LogSubject; +import org.apache.qpid.server.virtualhost.VirtualHost; public abstract class AbstractMessageStore implements MessageStore { - protected LogSubject _logSubject; + private LogSubject _logSubject; public void configure(VirtualHost virtualHost) throws Exception { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/store/ConfigurationRecoveryHandler.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/store/ConfigurationRecoveryHandler.java index 09e7fe0a11..fb67500da9 100755 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/store/ConfigurationRecoveryHandler.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/store/ConfigurationRecoveryHandler.java @@ -20,12 +20,12 @@ */ package org.apache.qpid.server.store; +import org.apache.qpid.framing.FieldTable; + import java.nio.ByteBuffer; import java.util.Map; import java.util.UUID; -import org.apache.qpid.framing.FieldTable; - public interface ConfigurationRecoveryHandler { QueueRecoveryHandler begin(MessageStore store); diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/store/DerbyMessageStore.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/store/DerbyMessageStore.java index 45083c1595..4d63136a9d 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/store/DerbyMessageStore.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/store/DerbyMessageStore.java @@ -20,6 +20,24 @@ */ 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.AMQStoreException; +import org.apache.qpid.framing.AMQShortString; +import org.apache.qpid.framing.FieldTable; +import org.apache.qpid.server.exchange.Exchange; +import org.apache.qpid.server.federation.Bridge; +import org.apache.qpid.server.federation.BrokerLink; +import org.apache.qpid.server.logging.LogSubject; +import org.apache.qpid.server.logging.actors.CurrentActor; +import org.apache.qpid.server.logging.messages.ConfigStoreMessages; +import org.apache.qpid.server.logging.messages.MessageStoreMessages; +import org.apache.qpid.server.logging.messages.TransactionLogMessages; +import org.apache.qpid.server.message.EnqueableMessage; +import org.apache.qpid.server.queue.AMQQueue; + import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; @@ -45,23 +63,6 @@ import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; -import org.apache.commons.configuration.Configuration; -import org.apache.log4j.Logger; -import org.apache.qpid.AMQException; -import org.apache.qpid.AMQStoreException; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.server.exchange.Exchange; -import org.apache.qpid.server.federation.Bridge; -import org.apache.qpid.server.federation.BrokerLink; -import org.apache.qpid.server.logging.LogSubject; -import org.apache.qpid.server.logging.actors.CurrentActor; -import org.apache.qpid.server.logging.messages.ConfigStoreMessages; -import org.apache.qpid.server.logging.messages.MessageStoreMessages; -import org.apache.qpid.server.logging.messages.TransactionLogMessages; -import org.apache.qpid.server.message.EnqueableMessage; -import org.apache.qpid.server.queue.AMQQueue; - /** * An implementation of a {@link MessageStore} that uses Apache Derby as the persistance * mechanism. @@ -91,7 +92,9 @@ public class DerbyMessageStore implements MessageStore, DurableConfigurationStor private static final String LINKS_TABLE_NAME = "QPID_LINKS"; private static final String BRIDGES_TABLE_NAME = "QPID_BRIDGES"; - + private static final String XID_TABLE_NAME = "QPID_XIDS"; + private static final String XID_ACTIONS_TABLE_NAME = "QPID_XID_ACTIONS"; + private static final int DB_VERSION = 3; @@ -189,6 +192,31 @@ public class DerbyMessageStore implements MessageStore, DurableConfigurationStor + "arguments )" + " values (?, ?, ?, ?, ?, ?)"; + private static final String CREATE_XIDS_TABLE = + "CREATE TABLE "+XID_TABLE_NAME+" ( format bigint not null," + + " global_id varchar(64) for bit data, branch_id varchar(64) for bit data, PRIMARY KEY ( format, " + + "global_id, branch_id ))"; + private static final String INSERT_INTO_XIDS = + "INSERT INTO "+XID_TABLE_NAME+" ( format, global_id, branch_id ) values (?, ?, ?)"; + private static final String DELETE_FROM_XIDS = "DELETE FROM " + XID_TABLE_NAME + + " WHERE format = ? and global_id = ? and branch_id = ?"; + private static final String SELECT_ALL_FROM_XIDS = "SELECT format, global_id, branch_id FROM " + XID_TABLE_NAME; + + + private static final String CREATE_XID_ACTIONS_TABLE = + "CREATE TABLE "+XID_ACTIONS_TABLE_NAME+" ( format bigint not null," + + " global_id varchar(64) for bit data not null, branch_id varchar(64) for bit data not null, " + + "action_type char not null, queue_name varchar(255) not null, message_id bigint not null" + + ", PRIMARY KEY ( " + + "format, global_id, branch_id, action_type, queue_name, message_id))"; + private static final String INSERT_INTO_XID_ACTIONS = + "INSERT INTO "+XID_ACTIONS_TABLE_NAME+" ( format, global_id, branch_id, action_type, " + + "queue_name, message_id ) values (?,?,?,?,?,?) "; + private static final String DELETE_FROM_XID_ACTIONS = "DELETE FROM " + XID_ACTIONS_TABLE_NAME + + " WHERE format = ? and global_id = ? and branch_id = ?"; + private static final String SELECT_ALL_FROM_XID_ACTIONS = + "SELECT action_type, queue_name, message_id FROM " + XID_ACTIONS_TABLE_NAME + + " WHERE format = ? and global_id = ? and branch_id = ?"; private static final String DERBY_SINGLE_DB_SHUTDOWN_CODE = "08006"; @@ -294,7 +322,8 @@ public class DerbyMessageStore implements MessageStore, DurableConfigurationStor _configured = true; } - recoverQueueEntries(recoveryHandler); + TransactionLogRecoveryHandler.DtxRecordRecoveryHandler dtxrh = recoverQueueEntries(recoveryHandler); + recoverXids(dtxrh); } @@ -349,7 +378,8 @@ public class DerbyMessageStore implements MessageStore, DurableConfigurationStor createMessageContentTable(conn); createLinkTable(conn); createBridgeTable(conn); - + createXidTable(conn); + createXidActionTable(conn); conn.close(); } @@ -518,8 +548,38 @@ public class DerbyMessageStore implements MessageStore, DurableConfigurationStor } } + private void createXidTable(final Connection conn) throws SQLException + { + if(!tableExists(XID_TABLE_NAME, conn)) + { + Statement stmt = conn.createStatement(); + try + { + stmt.execute(CREATE_XIDS_TABLE); + } + finally + { + stmt.close(); + } + } + } + private void createXidActionTable(final Connection conn) throws SQLException + { + if(!tableExists(XID_ACTIONS_TABLE_NAME, conn)) + { + Statement stmt = conn.createStatement(); + try + { + stmt.execute(CREATE_XID_ACTIONS_TABLE); + } + finally + { + stmt.close(); + } + } + } private boolean tableExists(final String tableName, final Connection conn) throws SQLException { @@ -650,12 +710,12 @@ public class DerbyMessageStore implements MessageStore, DurableConfigurationStor conn = newAutoCommitConnection(); PreparedStatement stmt = conn.prepareStatement(SELECT_ALL_FROM_BRIDGES); - stmt.setLong(1, linkId.getLeastSignificantBits()); - stmt.setLong(2, linkId.getMostSignificantBits()); - try { + stmt.setLong(1, linkId.getLeastSignificantBits()); + stmt.setLong(2, linkId.getMostSignificantBits()); + ResultSet rs = stmt.executeQuery(); try @@ -1110,11 +1170,7 @@ public class DerbyMessageStore implements MessageStore, DurableConfigurationStor insertStmt.setString(3, routingKey == null ? null : routingKey.toString()); if(args != null) { - /* This would be the Java 6 way of setting a Blob - Blob blobArgs = conn.createBlob(); - blobArgs.setBytes(0, args.getDataAsBytes()); - stmt.setBlob(4, blobArgs); - */ + // TODO - In Java 6 we could use create/set Blob byte[] bytes = args.getDataAsBytes(); ByteArrayInputStream bis = new ByteArrayInputStream(bytes); insertStmt.setBinaryStream(4, bis, bytes.length); @@ -1712,7 +1768,7 @@ public class DerbyMessageStore implements MessageStore, DurableConfigurationStor if (_logger.isDebugEnabled()) { - _logger.debug("Dequeuing message " + messageId + " on queue " + name );//+ "[Connection" + conn + "]"); + _logger.debug("Dequeuing message " + messageId + " on queue " + name ); } } finally @@ -1729,6 +1785,126 @@ public class DerbyMessageStore implements MessageStore, DurableConfigurationStor } + + private void removeXid(ConnectionWrapper connWrapper, long format, byte[] globalId, byte[] branchId) + throws AMQStoreException + { + Connection conn = connWrapper.getConnection(); + + + try + { + PreparedStatement stmt = conn.prepareStatement(DELETE_FROM_XIDS); + try + { + stmt.setLong(1,format); + stmt.setBytes(2,globalId); + stmt.setBytes(3,branchId); + int results = stmt.executeUpdate(); + + + + if(results != 1) + { + throw new AMQStoreException("Unable to find message with xid"); + } + } + finally + { + stmt.close(); + } + + stmt = conn.prepareStatement(DELETE_FROM_XID_ACTIONS); + try + { + stmt.setLong(1,format); + stmt.setBytes(2,globalId); + stmt.setBytes(3,branchId); + int results = stmt.executeUpdate(); + + } + finally + { + stmt.close(); + } + + } + catch (SQLException e) + { + _logger.error("Failed to dequeue: " + e.getMessage(), e); + throw new AMQStoreException("Error deleting enqueued message with xid", e); + } + + } + + + private void recordXid(ConnectionWrapper connWrapper, long format, byte[] globalId, byte[] branchId, + Transaction.Record[] enqueues, Transaction.Record[] dequeues) throws AMQStoreException + { + Connection conn = connWrapper.getConnection(); + + + try + { + + PreparedStatement stmt = conn.prepareStatement(INSERT_INTO_XIDS); + try + { + stmt.setLong(1,format); + stmt.setBytes(2, globalId); + stmt.setBytes(3, branchId); + stmt.executeUpdate(); + } + finally + { + stmt.close(); + } + + stmt = conn.prepareStatement(INSERT_INTO_XID_ACTIONS); + + try + { + stmt.setLong(1,format); + stmt.setBytes(2, globalId); + stmt.setBytes(3, branchId); + + if(enqueues != null) + { + stmt.setString(4, "E"); + for(Transaction.Record record : enqueues) + { + stmt.setString(5, record.getQueue().getResourceName()); + stmt.setLong(6, record.getMessage().getMessageNumber()); + stmt.executeUpdate(); + } + } + + if(dequeues != null) + { + stmt.setString(4, "D"); + for(Transaction.Record record : dequeues) + { + stmt.setString(5, record.getQueue().getResourceName()); + stmt.setLong(6, record.getMessage().getMessageNumber()); + stmt.executeUpdate(); + } + } + + } + finally + { + stmt.close(); + } + + } + catch (SQLException e) + { + _logger.error("Failed to enqueue: " + e.getMessage(), e); + throw new AMQStoreException("Error writing xid ", e); + } + + } + private static final class ConnectionWrapper { private final Connection _connection; @@ -1922,7 +2098,7 @@ public class DerbyMessageStore implements MessageStore, DurableConfigurationStor - private void recoverQueueEntries(TransactionLogRecoveryHandler recoveryHandler) throws SQLException + private TransactionLogRecoveryHandler.DtxRecordRecoveryHandler recoverQueueEntries(TransactionLogRecoveryHandler recoveryHandler) throws SQLException { Connection conn = newAutoCommitConnection(); try @@ -1953,7 +2129,7 @@ public class DerbyMessageStore implements MessageStore, DurableConfigurationStor stmt.close(); } - queueEntryHandler.completeQueueEntryRecovery(); + return queueEntryHandler.completeQueueEntryRecovery(); } finally { @@ -1961,6 +2137,166 @@ public class DerbyMessageStore implements MessageStore, DurableConfigurationStor } } + private static final class Xid + { + + private final long _format; + private final byte[] _globalId; + private final byte[] _branchId; + + public Xid(long format, byte[] globalId, byte[] branchId) + { + _format = format; + _globalId = globalId; + _branchId = branchId; + } + + public long getFormat() + { + return _format; + } + + public byte[] getGlobalId() + { + return _globalId; + } + + public byte[] getBranchId() + { + return _branchId; + } + } + + private static class RecordImpl implements MessageStore.Transaction.Record, TransactionLogResource, EnqueableMessage + { + + private final String _queueName; + private long _messageNumber; + + public RecordImpl(String queueName, long messageNumber) + { + _queueName = queueName; + _messageNumber = messageNumber; + } + + public TransactionLogResource getQueue() + { + return this; + } + + public EnqueableMessage getMessage() + { + return this; + } + + public long getMessageNumber() + { + return _messageNumber; + } + + public boolean isPersistent() + { + return true; + } + + public StoredMessage getStoredMessage() + { + throw new UnsupportedOperationException(); + } + + public String getResourceName() + { + return _queueName; + } + } + + private void recoverXids(TransactionLogRecoveryHandler.DtxRecordRecoveryHandler dtxrh) throws SQLException + { + Connection conn = newAutoCommitConnection(); + try + { + List xids = new ArrayList(); + + Statement stmt = conn.createStatement(); + try + { + ResultSet rs = stmt.executeQuery(SELECT_ALL_FROM_XIDS); + try + { + while(rs.next()) + { + + long format = rs.getLong(1); + byte[] globalId = rs.getBytes(2); + byte[] branchId = rs.getBytes(3); + xids.add(new Xid(format, globalId, branchId)); + } + } + finally + { + rs.close(); + } + } + finally + { + stmt.close(); + } + + + + for(Xid xid : xids) + { + List enqueues = new ArrayList(); + List dequeues = new ArrayList(); + + PreparedStatement pstmt = conn.prepareStatement(SELECT_ALL_FROM_XID_ACTIONS); + + try + { + pstmt.setLong(1, xid.getFormat()); + pstmt.setBytes(2, xid.getGlobalId()); + pstmt.setBytes(3, xid.getBranchId()); + + ResultSet rs = pstmt.executeQuery(); + try + { + while(rs.next()) + { + + String actionType = rs.getString(1); + String queueName = rs.getString(2); + long messageId = rs.getLong(3); + + RecordImpl record = new RecordImpl(queueName, messageId); + List records = "E".equals(actionType) ? enqueues : dequeues; + records.add(record); + } + } + finally + { + rs.close(); + } + } + finally + { + pstmt.close(); + } + + dtxrh.dtxRecord(xid.getFormat(), xid.getGlobalId(), xid.getBranchId(), + enqueues.toArray(new RecordImpl[enqueues.size()]), + dequeues.toArray(new RecordImpl[dequeues.size()])); + } + + + dtxrh.completeDtxRecordRecovery(); + } + finally + { + conn.close(); + } + + } + StorableMessageMetaData getMetaData(long messageId) throws SQLException { @@ -2031,11 +2367,8 @@ public class DerbyMessageStore implements MessageStore, DurableConfigurationStor stmt.setInt(3, offset+chunkData.length); - /* this would be the Java 6 way of doing things - Blob dataAsBlob = conn.createBlob(); - dataAsBlob.setBytes(1L, chunkData); - stmt.setBlob(3, dataAsBlob); - */ + // TODO in Java 6 we could just use blobs + ByteArrayInputStream bis = new ByteArrayInputStream(chunkData); stmt.setBinaryStream(4, bis, chunkData.length); stmt.executeUpdate(); @@ -2181,8 +2514,21 @@ public class DerbyMessageStore implements MessageStore, DurableConfigurationStor { DerbyMessageStore.this.abortTran(_connWrapper); } + + public void removeXid(long format, byte[] globalId, byte[] branchId) throws AMQStoreException + { + DerbyMessageStore.this.removeXid(_connWrapper, format, globalId, branchId); + } + + public void recordXid(long format, byte[] globalId, byte[] branchId, Record[] enqueues, Record[] dequeues) + throws AMQStoreException + { + DerbyMessageStore.this.recordXid(_connWrapper, format, globalId, branchId, enqueues, dequeues); + } } + + private class StoredDerbyMessage implements StoredMessage { @@ -2366,4 +2712,4 @@ public class DerbyMessageStore implements MessageStore, DurableConfigurationStor } } -} +} \ No newline at end of file diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/store/DurableConfigurationStore.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/store/DurableConfigurationStore.java index 9cd2567b7d..123ecd8145 100755 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/store/DurableConfigurationStore.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/store/DurableConfigurationStore.java @@ -21,6 +21,7 @@ package org.apache.qpid.server.store; import org.apache.commons.configuration.Configuration; + import org.apache.qpid.AMQStoreException; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.framing.FieldTable; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/store/MemoryMessageStore.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/store/MemoryMessageStore.java index c5393f73a2..b01e5aa954 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/store/MemoryMessageStore.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/store/MemoryMessageStore.java @@ -20,12 +20,9 @@ */ package org.apache.qpid.server.store; -import java.util.List; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicLong; - import org.apache.commons.configuration.Configuration; import org.apache.log4j.Logger; + import org.apache.qpid.AMQException; import org.apache.qpid.AMQStoreException; import org.apache.qpid.framing.AMQShortString; @@ -38,9 +35,12 @@ import org.apache.qpid.server.logging.actors.CurrentActor; import org.apache.qpid.server.logging.messages.ConfigStoreMessages; import org.apache.qpid.server.logging.messages.MessageStoreMessages; import org.apache.qpid.server.message.EnqueableMessage; -import org.apache.qpid.server.message.ServerMessage; import org.apache.qpid.server.queue.AMQQueue; +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicLong; + /** A simple message store that stores the messages in a threadsafe structure in memory. */ public class MemoryMessageStore implements MessageStore, DurableConfigurationStore { @@ -78,6 +78,14 @@ public class MemoryMessageStore implements MessageStore, DurableConfigurationSto { } + public void removeXid(long format, byte[] globalId, byte[] branchId) + { + } + + public void recordXid(long format, byte[] globalId, byte[] branchId, Record[] enqueues, Record[] dequeues) + { + } + }; public void configureConfigStore(String name, ConfigurationRecoveryHandler handler, Configuration configuration, LogSubject logSubject) throws Exception diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/store/MessageStore.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/store/MessageStore.java index 88c95ad65e..00bb0449d6 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/store/MessageStore.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/store/MessageStore.java @@ -20,9 +20,9 @@ */ package org.apache.qpid.server.store; +import org.apache.commons.configuration.Configuration; import org.apache.qpid.AMQStoreException; import org.apache.qpid.server.logging.LogSubject; -import org.apache.commons.configuration.Configuration; import org.apache.qpid.server.message.EnqueableMessage; /** @@ -125,7 +125,16 @@ public interface MessageStore void abortTran() throws AMQStoreException; + public static interface Record + { + TransactionLogResource getQueue(); + EnqueableMessage getMessage(); + } + + void removeXid(long format, byte[] globalId, byte[] branchId) throws AMQStoreException; + void recordXid(long format, byte[] globalId, byte[] branchId, Record[] enqueues, Record[] dequeues) + throws AMQStoreException; } public void configureTransactionLog(String name, diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/store/MessageStoreClosedException.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/store/MessageStoreClosedException.java index 3d1538c7eb..b0a736c66c 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/store/MessageStoreClosedException.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/store/MessageStoreClosedException.java @@ -1,6 +1,4 @@ -package org.apache.qpid.server.store; - -import org.apache.qpid.AMQException;/* +/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -21,6 +19,10 @@ import org.apache.qpid.AMQException;/* * */ +package org.apache.qpid.server.store; + +import org.apache.qpid.AMQException; + /** * NOTE: this class currently extends AMQException but * we should be using AMQExceptions internally in the code base for Protocol errors hence diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/store/TransactionLogRecoveryHandler.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/store/TransactionLogRecoveryHandler.java index 802596ed1e..48ca72718b 100755 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/store/TransactionLogRecoveryHandler.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/store/TransactionLogRecoveryHandler.java @@ -28,6 +28,13 @@ public interface TransactionLogRecoveryHandler { void queueEntry(String queuename, long messageId); - void completeQueueEntryRecovery(); + DtxRecordRecoveryHandler completeQueueEntryRecovery(); + } + + public static interface DtxRecordRecoveryHandler + { + void dtxRecord(long format, byte[] globalId, byte[] branchId, MessageStore.Transaction.Record[] enqueues, MessageStore.Transaction.Record[] dequeues); + + void completeDtxRecordRecovery(); } } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/AssignedSubscriptionMessageGroupManager.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/AssignedSubscriptionMessageGroupManager.java index f511cc0dc9..6b2dff7165 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/AssignedSubscriptionMessageGroupManager.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/AssignedSubscriptionMessageGroupManager.java @@ -20,11 +20,12 @@ */ package org.apache.qpid.server.subscription; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.QueueEntry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.apache.qpid.server.queue.AMQQueue; +import org.apache.qpid.server.queue.QueueEntry; + import java.util.Iterator; import java.util.concurrent.ConcurrentHashMap; @@ -47,7 +48,10 @@ public class AssignedSubscriptionMessageGroupManager implements MessageGroupMana private static int pow2(final int i) { int val = 1; - while(val < i) val<<=1; + while(val < i) + { + val<<=1; + } return val; } @@ -111,11 +115,15 @@ public class AssignedSubscriptionMessageGroupManager implements MessageGroupMana public boolean visit(final QueueEntry entry) { if(!entry.isAvailable()) + { return false; + } Object groupId = entry.getMessage().getMessageHeader().getHeader(_groupId); if(groupId == null) + { return false; + } Integer group = groupId.hashCode() & _groupMask; Subscription assignedSub = _groupMap.get(group); diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/ClientDeliveryMethod.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/ClientDeliveryMethod.java index fbc8b3af7d..632b59d3fa 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/ClientDeliveryMethod.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/ClientDeliveryMethod.java @@ -20,8 +20,8 @@ */ package org.apache.qpid.server.subscription; -import org.apache.qpid.server.queue.QueueEntry; import org.apache.qpid.AMQException; +import org.apache.qpid.server.queue.QueueEntry; public interface ClientDeliveryMethod { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/DefinedGroupMessageGroupManager.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/DefinedGroupMessageGroupManager.java index 689e48b4cf..62e94f6f2e 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/DefinedGroupMessageGroupManager.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/DefinedGroupMessageGroupManager.java @@ -20,12 +20,13 @@ */ package org.apache.qpid.server.subscription; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import org.apache.qpid.server.message.AMQMessageHeader; import org.apache.qpid.server.message.ServerMessage; import org.apache.qpid.server.queue.AMQQueue; import org.apache.qpid.server.queue.QueueEntry; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; @@ -188,7 +189,9 @@ public class DefinedGroupMessageGroupManager implements MessageGroupManager public boolean visit(final QueueEntry entry) { if(!entry.isAvailable()) + { return false; + } Object groupId = getKey(entry); diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/ExplicitAcceptDispositionChangeListener.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/ExplicitAcceptDispositionChangeListener.java index 80c5e2866c..cf2754862d 100755 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/ExplicitAcceptDispositionChangeListener.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/ExplicitAcceptDispositionChangeListener.java @@ -20,10 +20,11 @@ */ package org.apache.qpid.server.subscription; -import org.apache.qpid.server.transport.ServerSession; -import org.apache.qpid.server.queue.QueueEntry; import org.apache.log4j.Logger; +import org.apache.qpid.server.queue.QueueEntry; +import org.apache.qpid.server.transport.ServerSession; + class ExplicitAcceptDispositionChangeListener implements ServerSession.MessageDispositionChangeListener { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/ImplicitAcceptDispositionChangeListener.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/ImplicitAcceptDispositionChangeListener.java index a61b0b4e82..1e37675c98 100755 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/ImplicitAcceptDispositionChangeListener.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/ImplicitAcceptDispositionChangeListener.java @@ -20,10 +20,11 @@ */ package org.apache.qpid.server.subscription; -import org.apache.qpid.server.transport.ServerSession; -import org.apache.qpid.server.queue.QueueEntry; import org.apache.log4j.Logger; +import org.apache.qpid.server.queue.QueueEntry; +import org.apache.qpid.server.transport.ServerSession; + class ImplicitAcceptDispositionChangeListener implements ServerSession.MessageDispositionChangeListener { private static final Logger _logger = Logger.getLogger(ImplicitAcceptDispositionChangeListener.class); @@ -71,8 +72,6 @@ class ImplicitAcceptDispositionChangeListener implements ServerSession.MessageDi public boolean acquire() { boolean acquired = _entry.acquire(getSubscription()); - //TODO - why acknowledge here??? seems bizarre... - // getSubscription().getSession().acknowledge(getSubscription(), _entry); return acquired; } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/Subscription.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/Subscription.java index bc1be90531..66825caa24 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/Subscription.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/Subscription.java @@ -22,7 +22,6 @@ package org.apache.qpid.server.subscription; import org.apache.qpid.AMQException; import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.server.AMQChannel; import org.apache.qpid.server.logging.LogActor; import org.apache.qpid.server.queue.AMQQueue; import org.apache.qpid.server.queue.QueueEntry; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/SubscriptionFactory.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/SubscriptionFactory.java index 0fd7fdffe5..3659243cea 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/SubscriptionFactory.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/SubscriptionFactory.java @@ -20,22 +20,21 @@ */ package org.apache.qpid.server.subscription; -import java.util.Map; - import org.apache.qpid.AMQException; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.server.protocol.AMQProtocolSession; +import org.apache.qpid.server.AMQChannel; import org.apache.qpid.server.filter.FilterManager; import org.apache.qpid.server.flow.FlowCreditManager; import org.apache.qpid.server.flow.FlowCreditManager_0_10; -import org.apache.qpid.server.subscription.Subscription; +import org.apache.qpid.server.protocol.AMQProtocolSession; import org.apache.qpid.server.transport.ServerSession; -import org.apache.qpid.server.AMQChannel; import org.apache.qpid.transport.MessageAcceptMode; import org.apache.qpid.transport.MessageAcquireMode; import org.apache.qpid.transport.MessageFlowMode; +import java.util.Map; + /** * Allows the customisation of the creation of a subscription. This is typically done within an AMQQueue. This factory * primarily assists testing although in future more sophisticated subscribers may need a different subscription diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/SubscriptionFactoryImpl.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/SubscriptionFactoryImpl.java index 1622d63648..a2e30b6ae7 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/SubscriptionFactoryImpl.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/SubscriptionFactoryImpl.java @@ -20,9 +20,6 @@ */ package org.apache.qpid.server.subscription; -import java.util.Map; -import java.util.concurrent.atomic.AtomicLong; - import org.apache.qpid.AMQException; import org.apache.qpid.common.AMQPFilterTypes; import org.apache.qpid.framing.AMQShortString; @@ -38,6 +35,9 @@ import org.apache.qpid.transport.MessageAcceptMode; import org.apache.qpid.transport.MessageAcquireMode; import org.apache.qpid.transport.MessageFlowMode; +import java.util.Map; +import java.util.concurrent.atomic.AtomicLong; + public class SubscriptionFactoryImpl implements SubscriptionFactory { private static final AtomicLong SUB_ID_GENERATOR = new AtomicLong(0); diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/SubscriptionImpl.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/SubscriptionImpl.java index 23ae14eef1..1f25c215cc 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/SubscriptionImpl.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/SubscriptionImpl.java @@ -24,7 +24,6 @@ import org.apache.log4j.Logger; import org.apache.qpid.AMQException; import org.apache.qpid.common.AMQPFilterTypes; -import org.apache.qpid.common.ClientProperties; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.framing.FieldTable; import org.apache.qpid.server.AMQChannel; @@ -320,9 +319,6 @@ public abstract class SubscriptionImpl implements Subscription, FlowCreditManage private final Boolean _autoClose; - - private static final String CLIENT_PROPERTIES_INSTANCE = ClientProperties.instance.toString(); - private AMQQueue _queue; private final AtomicBoolean _deleted = new AtomicBoolean(false); @@ -479,10 +475,6 @@ public abstract class SubscriptionImpl implements Subscription, FlowCreditManage public boolean hasInterest(QueueEntry entry) { - - - - //check that the message hasn't been rejected if (entry.isRejectedBy(getSubscriptionID())) { @@ -490,27 +482,21 @@ public abstract class SubscriptionImpl implements Subscription, FlowCreditManage { _logger.debug("Subscription:" + this + " rejected message:" + entry); } -// return false; } if (_noLocal) { - AMQMessage message = (AMQMessage) entry.getMessage(); - //todo - client id should be recorded so we don't have to handle - // the case where this is null. - final Object publisher = message.getPublisherIdentifier(); + final Object publisherReference = message.getConnectionIdentifier(); // We don't want local messages so check to see if message is one we sent - Object localInstance = getProtocolSession(); + Object localReference = getProtocolSession().getReference(); - if(publisher.equals(localInstance)) + if(publisherReference != null && publisherReference.equals(localReference)) { return false; } - - } @@ -585,7 +571,7 @@ public abstract class SubscriptionImpl implements Subscription, FlowCreditManage public boolean wouldSuspend(QueueEntry msg) { - return !_creditManager.useCreditForMessage(msg.getMessage().getSize());//_channel.wouldSuspend(msg.getMessage()); + return !_creditManager.useCreditForMessage(msg.getMessage().getSize()); } public boolean trySendLock() diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/SubscriptionList.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/SubscriptionList.java index 3e6299cb8a..bf5ce31bd9 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/SubscriptionList.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/SubscriptionList.java @@ -20,11 +20,9 @@ */ package org.apache.qpid.server.subscription; -import org.apache.qpid.server.subscription.Subscription; - -import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; public class SubscriptionList { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/Subscription_0_10.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/Subscription_0_10.java index bde756dd03..76d975a789 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/Subscription_0_10.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/subscription/Subscription_0_10.java @@ -20,46 +20,58 @@ */ package org.apache.qpid.server.subscription; -import static org.apache.qpid.server.logging.subjects.LogSubjectFormat.SUBSCRIPTION_FORMAT; -import static org.apache.qpid.server.logging.subjects.LogSubjectFormat.QUEUE_FORMAT; - -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.BaseQueue; -import org.apache.qpid.server.queue.InboundMessageAdapter; -import org.apache.qpid.server.queue.QueueEntry; +import org.apache.qpid.AMQException; +import org.apache.qpid.framing.AMQShortString; +import org.apache.qpid.framing.BasicContentHeaderProperties; +import org.apache.qpid.framing.FieldTable; import org.apache.qpid.server.configuration.ConfigStore; import org.apache.qpid.server.configuration.ConfiguredObject; import org.apache.qpid.server.configuration.SessionConfig; import org.apache.qpid.server.configuration.SubscriptionConfig; import org.apache.qpid.server.configuration.SubscriptionConfigType; import org.apache.qpid.server.exchange.Exchange; -import org.apache.qpid.server.flow.FlowCreditManager; +import org.apache.qpid.server.filter.FilterManager; import org.apache.qpid.server.flow.CreditCreditManager; -import org.apache.qpid.server.flow.WindowCreditManager; +import org.apache.qpid.server.flow.FlowCreditManager; import org.apache.qpid.server.flow.FlowCreditManager_0_10; -import org.apache.qpid.server.filter.FilterManager; +import org.apache.qpid.server.flow.WindowCreditManager; +import org.apache.qpid.server.logging.LogActor; +import org.apache.qpid.server.logging.LogSubject; import org.apache.qpid.server.logging.actors.CurrentActor; import org.apache.qpid.server.logging.actors.GenericActor; import org.apache.qpid.server.logging.messages.ChannelMessages; import org.apache.qpid.server.logging.messages.SubscriptionMessages; -import org.apache.qpid.server.logging.LogActor; -import org.apache.qpid.server.logging.LogSubject; +import org.apache.qpid.server.message.AMQMessage; import org.apache.qpid.server.message.InboundMessage; -import org.apache.qpid.server.message.ServerMessage; import org.apache.qpid.server.message.MessageTransferMessage; -import org.apache.qpid.server.message.AMQMessage; +import org.apache.qpid.server.message.ServerMessage; +import org.apache.qpid.server.queue.AMQQueue; +import org.apache.qpid.server.queue.BaseQueue; +import org.apache.qpid.server.queue.InboundMessageAdapter; +import org.apache.qpid.server.queue.QueueEntry; import org.apache.qpid.server.transport.ServerSession; -import org.apache.qpid.server.txn.ServerTransaction; import org.apache.qpid.server.txn.AutoCommitTransaction; -import org.apache.qpid.transport.*; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.BasicContentHeaderProperties; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.AMQException; -import org.apache.qpid.transport.util.Logger; +import org.apache.qpid.server.txn.ServerTransaction; +import org.apache.qpid.transport.DeliveryProperties; +import org.apache.qpid.transport.Header; +import org.apache.qpid.transport.MessageAcceptMode; +import org.apache.qpid.transport.MessageAcquireMode; +import org.apache.qpid.transport.MessageCreditUnit; +import org.apache.qpid.transport.MessageDeliveryPriority; +import org.apache.qpid.transport.MessageFlowMode; +import org.apache.qpid.transport.MessageProperties; +import org.apache.qpid.transport.MessageTransfer; +import org.apache.qpid.transport.Method; +import org.apache.qpid.transport.Option; +import org.apache.qpid.transport.ReplyTo; +import org.apache.qpid.transport.Struct; import org.apache.qpid.url.AMQBindingURL; +import static org.apache.qpid.server.logging.subjects.LogSubjectFormat.QUEUE_FORMAT; +import static org.apache.qpid.server.logging.subjects.LogSubjectFormat.SUBSCRIPTION_FORMAT; + import java.net.URISyntaxException; +import java.nio.ByteBuffer; import java.text.MessageFormat; import java.util.Arrays; import java.util.Collections; @@ -67,13 +79,12 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; -import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.ConcurrentHashMap; -import java.nio.ByteBuffer; +import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; public class Subscription_0_10 implements Subscription, FlowCreditManager.FlowCreditManagerListener, SubscriptionConfig, LogSubject { @@ -387,6 +398,10 @@ public class Subscription_0_10 implements Subscription, FlowCreditManager.FlowCr { deliveryProps.setTimestamp(origDeliveryProps.getTimestamp()); } + if(origDeliveryProps.hasTtl()) + { + deliveryProps.setTtl(origDeliveryProps.getTtl()); + } } @@ -537,36 +552,8 @@ public class Subscription_0_10 implements Subscription, FlowCreditManager.FlowCr messageProps.setCorrelationId(serverMsg.getMessageHeader().getCorrelationId().getBytes()); } - // TODO - ReplyTo - - final Map appHeaders = new HashMap(); - - /*properties.getHeaders().processOverElements( - new FieldTable.FieldTableElementProcessor() - { - - public boolean processElement(String propertyName, AMQTypedValue value) - { - Object val = value.getValue(); - if(val instanceof AMQShortString) - { - val = val.toString(); - } - appHeaders.put(propertyName, val); - return true; - } - - public Object getResult() - { - return appHeaders; - } - }); - - - messageProps.setApplicationHeaders(appHeaders); -*/ Header header = new Header(deliveryProps, messageProps, null); xfr = batch ? new MessageTransfer(_destination,_acceptMode,_acquireMode,header, body, BATCHED) : new MessageTransfer(_destination,_acceptMode,_acquireMode,header, body); @@ -690,7 +677,10 @@ public class Subscription_0_10 implements Subscription, FlowCreditManager.FlowCr { entry.setRedelivered(); entry.routeToAlternate(); - + if(entry.isAcquiredBy(this)) + { + entry.discard(); + } } void release(final QueueEntry entry, final boolean setRedelivered) diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/transport/QpidAcceptor.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/transport/QpidAcceptor.java index abbc5a3805..637ea7dffc 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/transport/QpidAcceptor.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/transport/QpidAcceptor.java @@ -24,8 +24,8 @@ import org.apache.qpid.transport.network.NetworkTransport; public class QpidAcceptor { - NetworkTransport _transport; - String _protocol; + private NetworkTransport _transport; + private String _protocol; public QpidAcceptor(NetworkTransport transport, String protocol) { _transport = transport; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/transport/ServerConnection.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/transport/ServerConnection.java index 04cdbf2b25..c38f3d0761 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/transport/ServerConnection.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/transport/ServerConnection.java @@ -20,27 +20,6 @@ */ package org.apache.qpid.server.transport; -import static org.apache.qpid.server.logging.subjects.LogSubjectFormat.CONNECTION_FORMAT; -import static org.apache.qpid.server.logging.subjects.LogSubjectFormat.SOCKET_FORMAT; -import static org.apache.qpid.server.logging.subjects.LogSubjectFormat.USER_FORMAT; - -import java.util.concurrent.atomic.AtomicLong; - -import javax.management.JMException; - -import org.apache.qpid.server.management.ManagedObject; - -import org.apache.qpid.server.management.Managable; - -import java.security.Principal; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; -import java.util.concurrent.atomic.AtomicBoolean; - -import javax.security.auth.Subject; - import org.apache.qpid.AMQException; import org.apache.qpid.protocol.AMQConstant; import org.apache.qpid.server.configuration.ConnectionConfig; @@ -49,6 +28,8 @@ import org.apache.qpid.server.logging.LogSubject; import org.apache.qpid.server.logging.actors.CurrentActor; import org.apache.qpid.server.logging.actors.GenericActor; import org.apache.qpid.server.logging.messages.ConnectionMessages; +import org.apache.qpid.server.management.Managable; +import org.apache.qpid.server.management.ManagedObject; import org.apache.qpid.server.protocol.AMQConnectionModel; import org.apache.qpid.server.protocol.AMQSessionModel; import org.apache.qpid.server.security.AuthorizationHolder; @@ -62,8 +43,20 @@ import org.apache.qpid.transport.ExecutionException; import org.apache.qpid.transport.Method; import org.apache.qpid.transport.ProtocolEvent; import org.apache.qpid.transport.Session; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; + +import static org.apache.qpid.server.logging.subjects.LogSubjectFormat.CONNECTION_FORMAT; +import static org.apache.qpid.server.logging.subjects.LogSubjectFormat.SOCKET_FORMAT; +import static org.apache.qpid.server.logging.subjects.LogSubjectFormat.USER_FORMAT; + +import javax.management.JMException; +import javax.security.auth.Subject; +import java.security.Principal; +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicLong; public class ServerConnection extends Connection implements Managable, AMQConnectionModel, LogSubject, AuthorizationHolder { @@ -114,7 +107,7 @@ public class ServerConnection extends Connection implements Managable, AMQConnec { _onOpenTask.run(); } - _actor.message(ConnectionMessages.OPEN(getClientId(), "0-10", true, true)); + _actor.message(ConnectionMessages.OPEN(getClientId(), "0-10", getClientVersion(), true, true, true)); getVirtualHost().getConnectionRegistry().registerConnection(this); } @@ -495,4 +488,14 @@ public class ServerConnection extends Connection implements Managable, AMQConnec _mBean = null; } } + + public String getClientId() + { + return getConnectionDelegate().getClientId(); + } + + public String getClientVersion() + { + return getConnectionDelegate().getClientVersion(); + } } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/transport/ServerConnectionDelegate.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/transport/ServerConnectionDelegate.java index 66ed6f1e62..28d8cb2ec7 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/transport/ServerConnectionDelegate.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/transport/ServerConnectionDelegate.java @@ -20,17 +20,10 @@ */ package org.apache.qpid.server.transport; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.StringTokenizer; -import javax.security.sasl.SaslException; -import javax.security.sasl.SaslServer; +import static org.apache.qpid.transport.Connection.State.CLOSE_RCVD; + import org.apache.qpid.common.ServerPropertyNames; +import org.apache.qpid.properties.ConnectionStartProperties; import org.apache.qpid.protocol.ProtocolEngine; import org.apache.qpid.server.configuration.BrokerConfig; import org.apache.qpid.server.protocol.AMQConnectionModel; @@ -41,24 +34,25 @@ import org.apache.qpid.server.security.auth.AuthenticationResult; import org.apache.qpid.server.security.auth.AuthenticationResult.AuthenticationStatus; import org.apache.qpid.server.subscription.Subscription_0_10; import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.transport.Binary; -import org.apache.qpid.transport.Connection; -import org.apache.qpid.transport.ConnectionClose; -import org.apache.qpid.transport.ConnectionCloseCode; -import org.apache.qpid.transport.ConnectionOpen; -import org.apache.qpid.transport.ConnectionOpenOk; -import org.apache.qpid.transport.ConnectionStartOk; -import org.apache.qpid.transport.ConnectionTuneOk; -import org.apache.qpid.transport.ServerDelegate; -import org.apache.qpid.transport.Session; -import org.apache.qpid.transport.SessionAttach; -import org.apache.qpid.transport.SessionDelegate; -import org.apache.qpid.transport.SessionDetach; -import org.apache.qpid.transport.SessionDetachCode; -import org.apache.qpid.transport.SessionDetached; +import org.apache.qpid.transport.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.security.sasl.SaslException; +import javax.security.sasl.SaslServer; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.StringTokenizer; public class ServerConnectionDelegate extends ServerDelegate { + private static final Logger LOGGER = LoggerFactory.getLogger(ServerConnectionDelegate.class); + private final String _localFQDN; private final IApplicationRegistry _appRegistry; private int _maxNoOfChannels; @@ -140,17 +134,20 @@ public class ServerConnectionDelegate extends ServerDelegate } } + @Override public void connectionClose(Connection conn, ConnectionClose close) { + final ServerConnection sconn = (ServerConnection) conn; try { - ((ServerConnection) conn).logClosed(); + sconn.logClosed(); } finally { - super.connectionClose(conn, close); + sconn.closeCode(close); + sconn.setState(CLOSE_RCVD); + sendConnectionCloseOkAndCloseSender(conn); } - } public void connectionOpen(Connection conn, ConnectionOpen open) @@ -177,19 +174,19 @@ public class ServerConnectionDelegate extends ServerDelegate if (!vhost.getSecurityManager().accessVirtualhost(vhostName, ((ProtocolEngine) sconn.getConfig()).getRemoteAddress())) { - sconn.invoke(new ConnectionClose(ConnectionCloseCode.CONNECTION_FORCED, "Permission denied '"+vhostName+"'")); sconn.setState(Connection.State.CLOSING); + sconn.invoke(new ConnectionClose(ConnectionCloseCode.CONNECTION_FORCED, "Permission denied '"+vhostName+"'")); } else { - sconn.invoke(new ConnectionOpenOk(Collections.emptyList())); - sconn.setState(Connection.State.OPEN); + sconn.setState(Connection.State.OPEN); + sconn.invoke(new ConnectionOpenOk(Collections.emptyList())); } } else { - sconn.invoke(new ConnectionClose(ConnectionCloseCode.INVALID_PATH, "Unknown virtualhost '"+vhostName+"'")); sconn.setState(Connection.State.CLOSING); + sconn.invoke(new ConnectionClose(ConnectionCloseCode.INVALID_PATH, "Unknown virtualhost '"+vhostName+"'")); } } @@ -202,9 +199,9 @@ public class ServerConnectionDelegate extends ServerDelegate if (okChannelMax > getChannelMax()) { - _logger.error("Connection '" + sconn.getConnectionId() + "' being severed, " + + LOGGER.error("Connection '" + sconn.getConnectionId() + "' being severed, " + "client connectionTuneOk returned a channelMax (" + okChannelMax + - ") above the servers offered limit (" + getChannelMax() +")"); + ") above the server's offered limit (" + getChannelMax() +")"); //Due to the error we must forcefully close the connection without negotiation sconn.getSender().close(); @@ -234,23 +231,26 @@ public class ServerConnectionDelegate extends ServerDelegate @Override public void sessionDetach(Connection conn, SessionDetach dtc) { - // To ensure a clean detach, we unregister any remaining subscriptions. Unregister ensures - // that any in-progress delivery (SubFlushRunner/QueueRunner) is completed before the unregister + // To ensure a clean detach, we stop any remaining subscriptions. Stop ensures + // that any in-progress delivery (SubFlushRunner/QueueRunner) is completed before the stop // completes. - unregisterAllSubscriptions(conn, dtc); + stopAllSubscriptions(conn, dtc); + Session ssn = conn.getSession(dtc.getChannel()); + ((ServerSession)ssn).setClose(true); super.sessionDetach(conn, dtc); } - private void unregisterAllSubscriptions(Connection conn, SessionDetach dtc) + private void stopAllSubscriptions(Connection conn, SessionDetach dtc) { final ServerSession ssn = (ServerSession) conn.getSession(dtc.getChannel()); final Collection subs = ssn.getSubscriptions(); for (Subscription_0_10 subscription_0_10 : subs) { - ssn.unregister(subscription_0_10); + subscription_0_10.stop(); } } + @Override public void sessionAttach(final Connection conn, final SessionAttach atc) { @@ -258,8 +258,7 @@ public class ServerConnectionDelegate extends ServerDelegate if(isSessionNameUnique(atc.getName(), conn)) { - ssn = sessionAttachImpl(conn, atc); - conn.registerSession(ssn); + super.sessionAttach(conn, atc); ((ServerConnection)conn).checkForNotification(); } else @@ -299,4 +298,14 @@ public class ServerConnectionDelegate extends ServerDelegate { return _clientProperties; } + + public String getClientId() + { + return _clientProperties == null ? null : (String) _clientProperties.get(ConnectionStartProperties.CLIENT_ID_0_10); + } + + public String getClientVersion() + { + return _clientProperties == null ? null : (String) _clientProperties.get(ConnectionStartProperties.VERSION_0_10); + } } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/transport/ServerConnectionMBean.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/transport/ServerConnectionMBean.java index 17c7bed601..bb545164fb 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/transport/ServerConnectionMBean.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/transport/ServerConnectionMBean.java @@ -20,17 +20,6 @@ */ package org.apache.qpid.server.transport; -import java.io.IOException; -import java.util.Date; -import java.util.List; -import javax.management.JMException; -import javax.management.NotCompliantMBeanException; -import javax.management.openmbean.CompositeData; -import javax.management.openmbean.CompositeDataSupport; -import javax.management.openmbean.TabularData; -import javax.management.openmbean.TabularDataSupport; - -import org.apache.qpid.common.ClientProperties; import org.apache.qpid.management.common.mbeans.annotations.MBeanConstructor; import org.apache.qpid.management.common.mbeans.annotations.MBeanDescription; import org.apache.qpid.server.logging.actors.CurrentActor; @@ -39,6 +28,16 @@ import org.apache.qpid.server.management.AbstractAMQManagedConnectionObject; import org.apache.qpid.server.management.ManagedObject; import org.apache.qpid.server.protocol.AMQSessionModel; +import javax.management.JMException; +import javax.management.NotCompliantMBeanException; +import javax.management.openmbean.CompositeData; +import javax.management.openmbean.CompositeDataSupport; +import javax.management.openmbean.TabularData; +import javax.management.openmbean.TabularDataSupport; +import java.io.IOException; +import java.util.Date; +import java.util.List; + /** * This MBean class implements the management interface. In order to make more attributes, operations and notifications * available over JMX simply augment the ManagedConnection interface and add the appropriate implementation here. @@ -76,7 +75,7 @@ public class ServerConnectionMBean extends AbstractAMQManagedConnectionObject @Override public String getVersion() { - return String.valueOf(_serverConnection.getConnectionDelegate().getClientProperties().get(ClientProperties.version.toString())); + return String.valueOf(_serverConnection.getClientVersion()); } @Override @@ -132,7 +131,7 @@ public class ServerConnectionMBean extends AbstractAMQManagedConnectionObject } else if (session.isTransactional()) { - CurrentActor.set(new ManagementActor(_logActor.getRootMessageLogger())); + CurrentActor.set(new ManagementActor(getLogActor().getRootMessageLogger())); try { session.commit(); @@ -154,7 +153,7 @@ public class ServerConnectionMBean extends AbstractAMQManagedConnectionObject } else if (session.isTransactional()) { - CurrentActor.set(new ManagementActor(_logActor.getRootMessageLogger())); + CurrentActor.set(new ManagementActor(getLogActor().getRootMessageLogger())); try { session.rollback(); diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/transport/ServerSession.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/transport/ServerSession.java index 62a1e2b0f5..d63934e6be 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/transport/ServerSession.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/transport/ServerSession.java @@ -21,6 +21,11 @@ package org.apache.qpid.server.transport; import static org.apache.qpid.server.logging.subjects.LogSubjectFormat.CHANNEL_FORMAT; +import org.apache.qpid.server.message.InboundMessage; +import org.apache.qpid.server.message.MessageMetaData_0_10; +import org.apache.qpid.server.message.MessageTransferMessage; +import org.apache.qpid.server.txn.RollbackOnlyDtxException; +import org.apache.qpid.server.txn.TimeoutDtxException; import static org.apache.qpid.util.Serial.gt; import java.security.Principal; @@ -30,17 +35,21 @@ import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.SortedMap; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentSkipListMap; +import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; + import javax.security.auth.Subject; + import org.apache.qpid.AMQException; +import org.apache.qpid.AMQStoreException; import org.apache.qpid.protocol.AMQConstant; import org.apache.qpid.protocol.ProtocolEngine; import org.apache.qpid.server.configuration.ConfigStore; @@ -64,24 +73,19 @@ import org.apache.qpid.server.queue.QueueEntry; import org.apache.qpid.server.security.AuthorizationHolder; import org.apache.qpid.server.store.MessageStore; import org.apache.qpid.server.subscription.Subscription_0_10; +import org.apache.qpid.server.txn.AlreadyKnownDtxException; import org.apache.qpid.server.txn.AsyncAutoCommitTransaction; +import org.apache.qpid.server.txn.DistributedTransaction; +import org.apache.qpid.server.txn.DtxNotSelectedException; +import org.apache.qpid.server.txn.IncorrectDtxStateException; +import org.apache.qpid.server.txn.JoinAndResumeDtxException; import org.apache.qpid.server.txn.LocalTransaction; +import org.apache.qpid.server.txn.NotAssociatedDtxException; import org.apache.qpid.server.txn.ServerTransaction; +import org.apache.qpid.server.txn.SuspendAndFailDtxException; +import org.apache.qpid.server.txn.UnknownDtxBranchException; import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.transport.Binary; -import org.apache.qpid.transport.Connection; -import org.apache.qpid.transport.MessageCreditUnit; -import org.apache.qpid.transport.MessageFlow; -import org.apache.qpid.transport.MessageFlowMode; -import org.apache.qpid.transport.MessageSetFlowMode; -import org.apache.qpid.transport.MessageStop; -import org.apache.qpid.transport.MessageTransfer; -import org.apache.qpid.transport.Method; -import org.apache.qpid.transport.Range; -import org.apache.qpid.transport.RangeSet; -import org.apache.qpid.transport.RangeSetFactory; -import org.apache.qpid.transport.Session; -import org.apache.qpid.transport.SessionDelegate; +import org.apache.qpid.transport.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -100,13 +104,12 @@ public class ServerSession extends Session private long _createTime = System.currentTimeMillis(); private LogActor _actor = GenericActor.getInstance(this); - private final ConcurrentMap _blockingQueues = new ConcurrentHashMap(); + private final Set _blockingQueues = new ConcurrentSkipListSet(); private final AtomicBoolean _blocking = new AtomicBoolean(false); private ChannelLogSubject _logSubject; private final AtomicInteger _outstandingCredit = new AtomicInteger(UNLIMITED_CREDIT); - public static interface MessageDispositionChangeListener { public void onAccept(); @@ -356,7 +359,15 @@ public class ServerSession extends Session public void onClose() { - _transaction.rollback(); + if(_transaction instanceof LocalTransaction) + { + _transaction.rollback(); + } + else if(_transaction instanceof DistributedTransaction) + { + getVirtualHost().getDtxRegistry().endAssociations(this); + } + for(MessageDispositionChangeListener listener : _messageDispositionListenerMap.values()) { listener.onRelease(true); @@ -392,6 +403,9 @@ public class ServerSession extends Session public void onRollback() { + // The client has acknowledge the message and therefore have seen it. + // In the event of rollback, the message must be marked as redelivered. + entry.setRedelivered(); entry.release(); } }); @@ -452,6 +466,95 @@ public class ServerSession extends Session _txnStarts.incrementAndGet(); } + public void selectDtx() + { + _transaction = new DistributedTransaction(this, getMessageStore(), getVirtualHost()); + + } + + + public void startDtx(Xid xid, boolean join, boolean resume) + throws JoinAndResumeDtxException, + UnknownDtxBranchException, + AlreadyKnownDtxException, + DtxNotSelectedException + { + DistributedTransaction distributedTransaction = assertDtxTransaction(); + distributedTransaction.start(xid, join, resume); + } + + + public void endDtx(Xid xid, boolean fail, boolean suspend) + throws NotAssociatedDtxException, + UnknownDtxBranchException, + DtxNotSelectedException, + SuspendAndFailDtxException, TimeoutDtxException + { + DistributedTransaction distributedTransaction = assertDtxTransaction(); + distributedTransaction.end(xid, fail, suspend); + } + + + public long getTimeoutDtx(Xid xid) + throws UnknownDtxBranchException + { + return getVirtualHost().getDtxRegistry().getTimeout(xid); + } + + + public void setTimeoutDtx(Xid xid, long timeout) + throws UnknownDtxBranchException + { + getVirtualHost().getDtxRegistry().setTimeout(xid, timeout); + } + + + public void prepareDtx(Xid xid) + throws UnknownDtxBranchException, + IncorrectDtxStateException, AMQStoreException, RollbackOnlyDtxException, TimeoutDtxException + { + getVirtualHost().getDtxRegistry().prepare(xid); + } + + public void commitDtx(Xid xid, boolean onePhase) + throws UnknownDtxBranchException, + IncorrectDtxStateException, AMQStoreException, RollbackOnlyDtxException, TimeoutDtxException + { + getVirtualHost().getDtxRegistry().commit(xid, onePhase); + } + + + public void rollbackDtx(Xid xid) + throws UnknownDtxBranchException, + IncorrectDtxStateException, AMQStoreException, TimeoutDtxException + { + getVirtualHost().getDtxRegistry().rollback(xid); + } + + + public void forgetDtx(Xid xid) throws UnknownDtxBranchException, IncorrectDtxStateException + { + getVirtualHost().getDtxRegistry().forget(xid); + } + + public List recoverDtx() + { + return getVirtualHost().getDtxRegistry().recover(); + } + + private DistributedTransaction assertDtxTransaction() throws DtxNotSelectedException + { + if(_transaction instanceof DistributedTransaction) + { + return (DistributedTransaction) _transaction; + } + else + { + throw new DtxNotSelectedException(); + } + } + + public void commit() { _transaction.commit(); @@ -524,12 +627,12 @@ public class ServerSession extends Session public Principal getAuthorizedPrincipal() { - return ((ServerConnection) getConnection()).getAuthorizedPrincipal(); + return getConnection().getAuthorizedPrincipal(); } public Subject getAuthorizedSubject() { - return ((ServerConnection) getConnection()).getAuthorizedSubject(); + return getConnection().getAuthorizedSubject(); } public void addSessionCloseTask(Task task) @@ -544,7 +647,7 @@ public class ServerSession extends Session public Object getReference() { - return ((ServerConnection) getConnection()).getReference(); + return getConnection().getReference(); } public MessageStore getMessageStore() @@ -624,7 +727,7 @@ public class ServerSession extends Session public AMQConnectionModel getConnectionModel() { - return (ServerConnection) getConnection(); + return getConnection(); } public String getClientID() @@ -632,6 +735,12 @@ public class ServerSession extends Session return getConnection().getClientId(); } + @Override + public ServerConnection getConnection() + { + return (ServerConnection) super.getConnection(); + } + public LogActor getLogActor() { return _actor; @@ -676,7 +785,8 @@ public class ServerSession extends Session public void block(AMQQueue queue) { - if(_blockingQueues.putIfAbsent(queue, Boolean.TRUE) == null) + + if(_blockingQueues.add(queue)) { if(_blocking.compareAndSet(false,true)) @@ -694,7 +804,7 @@ public class ServerSession extends Session { if(_blockingQueues.remove(queue) && _blockingQueues.isEmpty()) { - if(_blocking.compareAndSet(true,false)) + if(_blocking.compareAndSet(true,false) && !isClosing()) { _actor.message(_logSubject, ChannelMessages.FLOW_REMOVED()); @@ -710,11 +820,19 @@ public class ServerSession extends Session } } + public boolean onSameConnection(InboundMessage inbound) + { + return ((inbound instanceof MessageTransferMessage) + && ((MessageTransferMessage)inbound).getConnectionReference() == getConnection().getReference()) + || ((inbound instanceof MessageMetaData_0_10) + && (((MessageMetaData_0_10)inbound).getConnectionReference())== getConnection().getReference()); + } + public String toLogString() { - long connectionId = getConnection() instanceof ServerConnection - ? ((ServerConnection) getConnection()).getConnectionId() + long connectionId = super.getConnection() instanceof ServerConnection + ? getConnection().getConnectionId() : -1; String remoteAddress = _connectionConfig instanceof ProtocolEngine @@ -749,6 +867,16 @@ public class ServerSession extends Session } } + void stopSubscriptions() + { + final Collection subscriptions = getSubscriptions(); + for (Subscription_0_10 subscription_0_10 : subscriptions) + { + subscription_0_10.stop(); + } + } + + public void receivedComplete() { final Collection subscriptions = getSubscriptions(); @@ -889,4 +1017,14 @@ public class ServerSession extends Session return _future.isComplete(); } } + + protected void setClose(boolean close) + { + super.setClose(close); + } + + public int compareTo(AMQSessionModel session) + { + return getId().toString().compareTo(session.getID().toString()); + } } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/transport/ServerSessionDelegate.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/transport/ServerSessionDelegate.java index 2eab65cf8a..c94a476712 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/transport/ServerSessionDelegate.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/transport/ServerSessionDelegate.java @@ -20,13 +20,10 @@ */ package org.apache.qpid.server.transport; -import java.nio.ByteBuffer; -import java.util.Collection; -import java.util.List; -import java.util.Map; - import org.apache.log4j.Logger; + import org.apache.qpid.AMQException; +import org.apache.qpid.AMQStoreException; import org.apache.qpid.AMQUnknownExchangeType; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.framing.FieldTable; @@ -54,10 +51,24 @@ import org.apache.qpid.server.store.MessageStore; import org.apache.qpid.server.store.StoredMessage; import org.apache.qpid.server.subscription.SubscriptionFactoryImpl; import org.apache.qpid.server.subscription.Subscription_0_10; +import org.apache.qpid.server.txn.AlreadyKnownDtxException; +import org.apache.qpid.server.txn.DtxNotSelectedException; +import org.apache.qpid.server.txn.IncorrectDtxStateException; +import org.apache.qpid.server.txn.JoinAndResumeDtxException; +import org.apache.qpid.server.txn.NotAssociatedDtxException; +import org.apache.qpid.server.txn.RollbackOnlyDtxException; import org.apache.qpid.server.txn.ServerTransaction; +import org.apache.qpid.server.txn.SuspendAndFailDtxException; +import org.apache.qpid.server.txn.TimeoutDtxException; +import org.apache.qpid.server.txn.UnknownDtxBranchException; import org.apache.qpid.server.virtualhost.VirtualHost; import org.apache.qpid.transport.*; +import java.nio.ByteBuffer; +import java.util.Collection; +import java.util.List; +import java.util.Map; + public class ServerSessionDelegate extends SessionDelegate { private static final Logger LOGGER = Logger.getLogger(ServerSessionDelegate.class); @@ -154,7 +165,12 @@ public class ServerSessionDelegate extends SessionDelegate @Override public void messageSubscribe(Session session, MessageSubscribe method) { - //TODO - work around broken Python tests + /* + TODO - work around broken Python tests + Correct code should read like + if not hasAcceptMode() exception ILLEGAL_ARGUMENT "Accept-mode not supplied" + else if not method.hasAcquireMode() exception ExecutionErrorCode.ILLEGAL_ARGUMENT, "Acquire-mode not supplied" + */ if(!method.hasAcceptMode()) { method.setAcceptMode(MessageAcceptMode.EXPLICIT); @@ -165,15 +181,7 @@ public class ServerSessionDelegate extends SessionDelegate } - /* if(!method.hasAcceptMode()) - { - exception(session,method,ExecutionErrorCode.ILLEGAL_ARGUMENT, "Accept-mode not supplied"); - } - else if(!method.hasAcquireMode()) - { - exception(session,method,ExecutionErrorCode.ILLEGAL_ARGUMENT, "Acquire-mode not supplied"); - } - else */if(!method.hasQueue()) + if(!method.hasQueue()) { exception(session,method,ExecutionErrorCode.ILLEGAL_ARGUMENT, "queue not supplied"); } @@ -201,6 +209,10 @@ public class ServerSessionDelegate extends SessionDelegate { exception(session,method,ExecutionErrorCode.RESOURCE_LOCKED, "Exclusive Queue: " + queueName + " owned exclusively by another session"); } + else if(queue.isExclusive() && queue.getExclusiveOwningSession() != null && queue.getExclusiveOwningSession() != session) + { + exception(session,method,ExecutionErrorCode.RESOURCE_LOCKED, "Exclusive Queue: " + queueName + " owned exclusively by another session"); + } else { if(queue.isExclusive()) @@ -223,7 +235,6 @@ public class ServerSessionDelegate extends SessionDelegate } }); } - } FlowCreditManager_0_10 creditManager = new WindowCreditManager(0L,0L); @@ -283,6 +294,7 @@ public class ServerSessionDelegate extends SessionDelegate } final MessageMetaData_0_10 messageMetaData = new MessageMetaData_0_10(xfr); + messageMetaData.setConnectionReference(((ServerSession)ssn).getReference()); if (!getVirtualHost(ssn).getSecurityManager().authorisePublish(messageMetaData.isImmediate(), messageMetaData.getRoutingKey(), exchange.getName())) { @@ -428,6 +440,235 @@ public class ServerSessionDelegate extends SessionDelegate ((ServerSession)session).rollback(); } + @Override + public void dtxSelect(Session session, DtxSelect method) + { + // TODO - check current tx mode + ((ServerSession)session).selectDtx(); + } + + @Override + public void dtxStart(Session session, DtxStart method) + { + XaResult result = new XaResult(); + result.setStatus(DtxXaStatus.XA_OK); + try + { + ((ServerSession)session).startDtx(method.getXid(), method.getJoin(), method.getResume()); + session.executionResult(method.getId(), result); + } + catch(JoinAndResumeDtxException e) + { + exception(session, method, ExecutionErrorCode.COMMAND_INVALID, e.getMessage()); + } + catch(UnknownDtxBranchException e) + { + exception(session, method, ExecutionErrorCode.NOT_ALLOWED, "Unknown xid " + method.getXid()); + } + catch(AlreadyKnownDtxException e) + { + exception(session, method, ExecutionErrorCode.NOT_ALLOWED, "Xid already started an neither join nor " + + "resume set" + method.getXid()); + } + catch(DtxNotSelectedException e) + { + exception(session, method, ExecutionErrorCode.COMMAND_INVALID, e.getMessage()); + } + + } + + @Override + public void dtxEnd(Session session, DtxEnd method) + { + XaResult result = new XaResult(); + result.setStatus(DtxXaStatus.XA_OK); + try + { + try + { + ((ServerSession)session).endDtx(method.getXid(), method.getFail(), method.getSuspend()); + } + catch (TimeoutDtxException e) + { + result.setStatus(DtxXaStatus.XA_RBTIMEOUT); + } + session.executionResult(method.getId(), result); + } + catch(UnknownDtxBranchException e) + { + exception(session, method, ExecutionErrorCode.ILLEGAL_STATE, e.getMessage()); + } + catch(NotAssociatedDtxException e) + { + exception(session, method, ExecutionErrorCode.ILLEGAL_STATE, e.getMessage()); + } + catch(DtxNotSelectedException e) + { + exception(session, method, ExecutionErrorCode.ILLEGAL_STATE, e.getMessage()); + } + catch(SuspendAndFailDtxException e) + { + exception(session, method, ExecutionErrorCode.COMMAND_INVALID, e.getMessage()); + } + + } + + @Override + public void dtxCommit(Session session, DtxCommit method) + { + XaResult result = new XaResult(); + result.setStatus(DtxXaStatus.XA_OK); + try + { + try + { + ((ServerSession)session).commitDtx(method.getXid(), method.getOnePhase()); + } + catch (RollbackOnlyDtxException e) + { + result.setStatus(DtxXaStatus.XA_RBROLLBACK); + } + catch (TimeoutDtxException e) + { + result.setStatus(DtxXaStatus.XA_RBTIMEOUT); + } + session.executionResult(method.getId(), result); + } + catch(UnknownDtxBranchException e) + { + exception(session, method, ExecutionErrorCode.NOT_FOUND, e.getMessage()); + } + catch(IncorrectDtxStateException e) + { + exception(session, method, ExecutionErrorCode.ILLEGAL_STATE, e.getMessage()); + } + catch(AMQStoreException e) + { + exception(session, method, ExecutionErrorCode.INTERNAL_ERROR, e.getMessage()); + } + } + + @Override + public void dtxForget(Session session, DtxForget method) + { + try + { + ((ServerSession)session).forgetDtx(method.getXid()); + } + catch(UnknownDtxBranchException e) + { + exception(session, method, ExecutionErrorCode.NOT_FOUND, e.getMessage()); + } + catch(IncorrectDtxStateException e) + { + exception(session, method, ExecutionErrorCode.ILLEGAL_STATE, e.getMessage()); + } + + } + + @Override + public void dtxGetTimeout(Session session, DtxGetTimeout method) + { + GetTimeoutResult result = new GetTimeoutResult(); + try + { + result.setTimeout(((ServerSession) session).getTimeoutDtx(method.getXid())); + session.executionResult(method.getId(), result); + } + catch(UnknownDtxBranchException e) + { + exception(session, method, ExecutionErrorCode.NOT_FOUND, e.getMessage()); + } + } + + @Override + public void dtxPrepare(Session session, DtxPrepare method) + { + XaResult result = new XaResult(); + result.setStatus(DtxXaStatus.XA_OK); + try + { + try + { + ((ServerSession)session).prepareDtx(method.getXid()); + } + catch (RollbackOnlyDtxException e) + { + result.setStatus(DtxXaStatus.XA_RBROLLBACK); + } + catch (TimeoutDtxException e) + { + result.setStatus(DtxXaStatus.XA_RBTIMEOUT); + } + session.executionResult((int) method.getId(), result); + } + catch(UnknownDtxBranchException e) + { + exception(session, method, ExecutionErrorCode.NOT_FOUND, e.getMessage()); + } + catch(IncorrectDtxStateException e) + { + exception(session, method, ExecutionErrorCode.ILLEGAL_STATE, e.getMessage()); + } + catch(AMQStoreException e) + { + exception(session, method, ExecutionErrorCode.INTERNAL_ERROR, e.getMessage()); + } + } + + @Override + public void dtxRecover(Session session, DtxRecover method) + { + RecoverResult result = new RecoverResult(); + List inDoubt = ((ServerSession)session).recoverDtx(); + result.setInDoubt(inDoubt); + session.executionResult(method.getId(), result); + } + + @Override + public void dtxRollback(Session session, DtxRollback method) + { + + XaResult result = new XaResult(); + result.setStatus(DtxXaStatus.XA_OK); + try + { + try + { + ((ServerSession)session).rollbackDtx(method.getXid()); + } + catch (TimeoutDtxException e) + { + result.setStatus(DtxXaStatus.XA_RBTIMEOUT); + } + session.executionResult(method.getId(), result); + } + catch(UnknownDtxBranchException e) + { + exception(session, method, ExecutionErrorCode.NOT_FOUND, e.getMessage()); + } + catch(IncorrectDtxStateException e) + { + exception(session, method, ExecutionErrorCode.ILLEGAL_STATE, e.getMessage()); + } + catch(AMQStoreException e) + { + exception(session, method, ExecutionErrorCode.INTERNAL_ERROR, e.getMessage()); + } + } + + @Override + public void dtxSetTimeout(Session session, DtxSetTimeout method) + { + try + { + ((ServerSession)session).setTimeoutDtx(method.getXid(), method.getTimeout()); + } + catch(UnknownDtxBranchException e) + { + exception(session, method, ExecutionErrorCode.NOT_FOUND, e.getMessage()); + } + } @Override public void executionSync(final Session ssn, final ExecutionSync sync) @@ -465,9 +706,9 @@ public class ServerSessionDelegate extends SessionDelegate } else { - if(!exchange.getTypeShortString().toString().equals(method.getType())) + if(!exchange.getTypeShortString().toString().equals(method.getType()) && (method.getType() != null && method.getType().length() > 0)) { - exception(session, method, ExecutionErrorCode.NOT_ALLOWED, "Cannot redeclare with a different exchange type"); + exception(session, method, ExecutionErrorCode.NOT_ALLOWED, "Attempt to redeclare exchange: " + exchangeName + " of type " + exchange.getTypeShortString() + " to " + method.getType() +"."); } } @@ -476,48 +717,96 @@ public class ServerSessionDelegate extends SessionDelegate { if (exchange == null) { - ExchangeRegistry exchangeRegistry = getExchangeRegistry(session); - ExchangeFactory exchangeFactory = virtualHost.getExchangeFactory(); + if(exchangeName.startsWith("amq.")) + { + exception(session, method, ExecutionErrorCode.NOT_ALLOWED, + "Attempt to declare exchange: " + exchangeName + + " which begins with reserved prefix 'amq.'."); + } + else if(exchangeName.startsWith("qpid.")) + { + exception(session, method, ExecutionErrorCode.NOT_ALLOWED, + "Attempt to declare exchange: " + exchangeName + + " which begins with reserved prefix 'qpid.'."); + } + else + { + ExchangeRegistry exchangeRegistry = getExchangeRegistry(session); + ExchangeFactory exchangeFactory = virtualHost.getExchangeFactory(); - try - { + try + { + + exchange = exchangeFactory.createExchange(method.getExchange(), + method.getType(), + method.getDurable(), + method.getAutoDelete()); + + String alternateExchangeName = method.getAlternateExchange(); + boolean validAlternate; + if(alternateExchangeName != null && alternateExchangeName.length() != 0) + { + Exchange alternate = getExchange(session, alternateExchangeName); + if(alternate == null) + { + validAlternate = false; + } + else + { + exchange.setAlternateExchange(alternate); + validAlternate = true; + } + } + else + { + validAlternate = true; + } - exchange = exchangeFactory.createExchange(method.getExchange(), - method.getType(), - method.getDurable(), - method.getAutoDelete()); + if(validAlternate) + { + if (exchange.isDurable()) + { + DurableConfigurationStore store = virtualHost.getDurableConfigurationStore(); + store.createExchange(exchange); + } - String alternateExchangeName = method.getAlternateExchange(); - if(alternateExchangeName != null && alternateExchangeName.length() != 0) + exchangeRegistry.registerExchange(exchange); + } + else + { + exception(session, method, ExecutionErrorCode.NOT_FOUND, + "Unknown alternate exchange " + alternateExchangeName); + } + } + catch(AMQUnknownExchangeType e) { - Exchange alternate = getExchange(session, alternateExchangeName); - exchange.setAlternateExchange(alternate); + exception(session, method, ExecutionErrorCode.NOT_FOUND, "Unknown Exchange Type: " + method.getType()); } - - if (exchange.isDurable()) + catch (AMQException e) { - DurableConfigurationStore store = virtualHost.getDurableConfigurationStore(); - store.createExchange(exchange); + exception(session, method, e, "Cannot declare exchange '" + exchangeName); } - - exchangeRegistry.registerExchange(exchange); - } - catch(AMQUnknownExchangeType e) - { - exception(session, method, ExecutionErrorCode.NOT_FOUND, "Unknown Exchange Type: " + method.getType()); - } - catch (AMQException e) - { - exception(session, method, e, "Cannot declare exchange '" + exchangeName); } } else { if(!exchange.getTypeShortString().toString().equals(method.getType())) { - exception(session, method, ExecutionErrorCode.NOT_ALLOWED, "Cannot redeclare with a different exchange type"); + exception(session, method, ExecutionErrorCode.NOT_ALLOWED, + "Attempt to redeclare exchange: " + exchangeName + + " of type " + exchange.getTypeShortString() + + " to " + method.getType() +"."); + } + else if(method.hasAlternateExchange() + && (exchange.getAlternateExchange() == null || + !method.getAlternateExchange().equals(exchange.getAlternateExchange().getName()))) + { + exception(session, method, ExecutionErrorCode.NOT_ALLOWED, + "Attempt to change alternate exchange of: " + exchangeName + + " from " + exchange.getAlternateExchange() + + " to " + method.getAlternateExchange() +"."); } } @@ -710,15 +999,10 @@ public class ServerSessionDelegate extends SessionDelegate { exception(session, method, ExecutionErrorCode.INVALID_ARGUMENT, "Bind not allowed for default exchange"); } -/* - else if (!method.hasBindingKey()) - { - exception(session, method, ExecutionErrorCode.ILLEGAL_ARGUMENT, "binding-key not set"); - } -*/ else { //TODO - here because of non-compiant python tests + // should raise exception ILLEGAL_ARGUMENT "binding-key not set" if (!method.hasBindingKey()) { method.setBindingKey(method.getQueue()); @@ -739,10 +1023,7 @@ public class ServerSessionDelegate extends SessionDelegate } else { - AMQShortString routingKey = new AMQShortString(method.getBindingKey()); - FieldTable fieldTable = FieldTable.convertToFieldTable(method.getArguments()); - - if (!exchange.isBound(routingKey, fieldTable, queue)) + if (!exchange.isBound(method.getBindingKey(), method.getArguments(), queue)) { try { @@ -854,12 +1135,6 @@ public class ServerSessionDelegate extends SessionDelegate if(method.hasBindingKey()) { - if(method.hasArguments()) - { - FieldTable args = FieldTable.convertToFieldTable(method.getArguments()); - - result.setArgsNotMatched(!exchange.isBound(new AMQShortString(method.getBindingKey()), args, queue)); - } if(queueMatched) { result.setKeyNotMatched(!exchange.isBound(method.getBindingKey(), queue)); @@ -868,23 +1143,28 @@ public class ServerSessionDelegate extends SessionDelegate { result.setKeyNotMatched(!exchange.isBound(method.getBindingKey())); } + + if(method.hasArguments()) + { + result.setArgsNotMatched(!exchange.isBound(result.getKeyNotMatched() ? null : method.getBindingKey(), method.getArguments(), queueMatched ? queue : null)); + } + } else if (method.hasArguments()) { - // TODO - + result.setArgsNotMatched(!exchange.isBound(null, method.getArguments(), queueMatched ? queue : null)); } - result.setQueueNotMatched(!exchange.isBound(queue)); - } else if(exchange != null && method.hasBindingKey()) { + result.setKeyNotMatched(!exchange.isBound(method.getBindingKey())); + if(method.hasArguments()) { - // TODO + result.setArgsNotMatched(!exchange.isBound(result.getKeyNotMatched() ? null : method.getBindingKey(), method.getArguments(), queue)); } - result.setKeyNotMatched(!exchange.isBound(method.getBindingKey())); + } @@ -893,11 +1173,15 @@ public class ServerSessionDelegate extends SessionDelegate { if(method.hasArguments()) { - // TODO + result.setArgsNotMatched(!exchange.isBound(method.getBindingKey(), method.getArguments(), null)); } result.setKeyNotMatched(!exchange.isBound(method.getBindingKey())); } + else if(exchange != null && method.hasArguments()) + { + result.setArgsNotMatched(!exchange.isBound(null, method.getArguments(), null)); + } session.executionResult((int) method.getId(), result); @@ -1141,6 +1425,10 @@ public class ServerSessionDelegate extends SessionDelegate { exception(session,method,ExecutionErrorCode.RESOURCE_LOCKED, "Exclusive Queue: " + queueName + " owned exclusively by another session"); } + else if(queue.isExclusive() && queue.getExclusiveOwningSession() != null && queue.getExclusiveOwningSession() != session) + { + exception(session,method,ExecutionErrorCode.RESOURCE_LOCKED, "Exclusive Queue: " + queueName + " owned exclusively by another session"); + } else if (method.getIfEmpty() && !queue.isEmpty()) { exception(session, method, ExecutionErrorCode.PRECONDITION_FAILED, "Queue " + queueName + " not empty"); @@ -1287,8 +1575,9 @@ public class ServerSessionDelegate extends SessionDelegate ServerSession serverSession = (ServerSession)session; - serverSession.unregisterSubscriptions(); + serverSession.stopSubscriptions(); serverSession.onClose(); + serverSession.unregisterSubscriptions(); } @Override diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/AlreadyKnownDtxException.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/AlreadyKnownDtxException.java new file mode 100644 index 0000000000..faa4ec592f --- /dev/null +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/AlreadyKnownDtxException.java @@ -0,0 +1,32 @@ +/* + * + * 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.transport.Xid; + +public class AlreadyKnownDtxException extends DtxException +{ + public AlreadyKnownDtxException(Xid id) + { + super("Xid " + id + " cannot be started as it is already known"); + } +} diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/AsyncAutoCommitTransaction.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/AsyncAutoCommitTransaction.java index 7e238aeadc..a062c6732f 100755 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/AsyncAutoCommitTransaction.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/AsyncAutoCommitTransaction.java @@ -21,6 +21,7 @@ package org.apache.qpid.server.txn; import org.apache.log4j.Logger; + import org.apache.qpid.AMQException; import org.apache.qpid.AMQStoreException; import org.apache.qpid.server.message.EnqueableMessage; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/AutoCommitTransaction.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/AutoCommitTransaction.java index ad2a299108..597797b5f8 100755 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/AutoCommitTransaction.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/AutoCommitTransaction.java @@ -20,11 +20,8 @@ */ package org.apache.qpid.server.txn; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - import org.apache.log4j.Logger; + import org.apache.qpid.AMQException; import org.apache.qpid.AMQStoreException; import org.apache.qpid.server.message.EnqueableMessage; @@ -33,6 +30,9 @@ import org.apache.qpid.server.queue.BaseQueue; import org.apache.qpid.server.queue.QueueEntry; import org.apache.qpid.server.store.MessageStore; +import java.util.Collection; +import java.util.List; + /** * An implementation of ServerTransaction where each enqueue/dequeue * operation takes place within it own transaction. diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/DistributedTransaction.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/DistributedTransaction.java new file mode 100644 index 0000000000..36f5f7b58f --- /dev/null +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/DistributedTransaction.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.server.txn; + +import org.apache.qpid.server.message.EnqueableMessage; +import org.apache.qpid.server.protocol.AMQSessionModel; +import org.apache.qpid.server.queue.BaseQueue; +import org.apache.qpid.server.queue.QueueEntry; +import org.apache.qpid.server.store.MessageStore; +import org.apache.qpid.server.virtualhost.VirtualHost; +import org.apache.qpid.transport.Xid; + +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +public class DistributedTransaction implements ServerTransaction +{ + + private final AutoCommitTransaction _autoCommitTransaction; + + private volatile MessageStore.Transaction _transaction; + + private long _txnStartTime = 0L; + + private DtxBranch _branch; + private AMQSessionModel _session; + private VirtualHost _vhost; + + + public DistributedTransaction(AMQSessionModel session, MessageStore store, VirtualHost vhost) + { + _session = session; + _vhost = vhost; + _autoCommitTransaction = new AutoCommitTransaction(vhost.getMessageStore()); + } + + public long getTransactionStartTime() + { + return _txnStartTime; + } + + public void addPostTransactionAction(Action postTransactionAction) + { + if(_branch != null) + { + _branch.addPostTransactionAcion(postTransactionAction); + } + else + { + _autoCommitTransaction.addPostTransactionAction(postTransactionAction); + } + } + + public void dequeue(BaseQueue queue, EnqueableMessage message, Action postTransactionAction) + { + if(_branch != null) + { + _branch.dequeue(queue, message); + _branch.addPostTransactionAcion(postTransactionAction); + } + else + { + _autoCommitTransaction.dequeue(queue, message, postTransactionAction); + } + } + + public void dequeue(Collection messages, Action postTransactionAction) + { + if(_branch != null) + { + for(QueueEntry entry : messages) + { + _branch.dequeue(entry.getQueue(), entry.getMessage()); + } + _branch.addPostTransactionAcion(postTransactionAction); + } + else + { + _autoCommitTransaction.dequeue(messages, postTransactionAction); + } + } + + public void enqueue(BaseQueue queue, EnqueableMessage message, Action postTransactionAction) + { + if(_branch != null) + { + _branch.enqueue(queue, message); + _branch.addPostTransactionAcion(postTransactionAction); + enqueue(Collections.singletonList(queue), message, postTransactionAction, System.currentTimeMillis()); + } + else + { + _autoCommitTransaction.enqueue(queue, message, postTransactionAction); + } + } + + public void enqueue(List queues, EnqueableMessage message, + Action postTransactionAction, long currentTime) + { + if(_branch != null) + { + for(BaseQueue queue : queues) + { + _branch.enqueue(queue, message); + } + _branch.addPostTransactionAcion(postTransactionAction); + } + else + { + _autoCommitTransaction.enqueue(queues, message, postTransactionAction, currentTime); + } + } + + public void commit() + { + throw new IllegalStateException("Cannot call tx.commit() on a distributed transaction"); + } + + public void commit(Runnable immediatePostTransactionAction) + { + throw new IllegalStateException("Cannot call tx.commit() on a distributed transaction"); + } + + public void rollback() + { + throw new IllegalStateException("Cannot call tx.rollback() on a distributed transaction"); + } + + public boolean isTransactional() + { + return _branch != null; + } + + public void start(Xid id, boolean join, boolean resume) + throws UnknownDtxBranchException, AlreadyKnownDtxException, JoinAndResumeDtxException + { + if(join && resume) + { + throw new JoinAndResumeDtxException(id); + } + + DtxBranch branch = _vhost.getDtxRegistry().getBranch(id); + + if(branch == null) + { + if(join || resume) + { + throw new UnknownDtxBranchException(id); + } + branch = new DtxBranch(id,_vhost.getMessageStore(), _vhost); + if(_vhost.getDtxRegistry().registerBranch(branch)) + { + _branch = branch; + branch.associateSession(_session); + } + else + { + throw new AlreadyKnownDtxException(id); + } + } + else + { + if(join) + { + branch.associateSession(_session); + } + else if(resume) + { + branch.resumeSession(_session); + } + else + { + throw new AlreadyKnownDtxException(id); + } + _branch = branch; + } + } + + public void end(Xid id, boolean fail, boolean suspend) + throws UnknownDtxBranchException, NotAssociatedDtxException, SuspendAndFailDtxException, TimeoutDtxException + { + DtxBranch branch = _vhost.getDtxRegistry().getBranch(id); + + if(suspend && fail) + { + branch.disassociateSession(_session); + _branch = null; + throw new SuspendAndFailDtxException(id); + } + + + if(branch == null) + { + throw new UnknownDtxBranchException(id); + } + else + { + if(!branch.isAssociated(_session)) + { + throw new NotAssociatedDtxException(id); + } + if(branch.expired() || branch.getState() == DtxBranch.State.TIMEDOUT) + { + branch.disassociateSession(_session); + throw new TimeoutDtxException(id); + } + + if(suspend) + { + branch.suspendSession(_session); + } + else + { + if(fail) + { + branch.setState(DtxBranch.State.ROLLBACK_ONLY); + } + branch.disassociateSession(_session); + } + + _branch = null; + + } + } + +} diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/DtxBranch.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/DtxBranch.java new file mode 100644 index 0000000000..99bb639261 --- /dev/null +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/DtxBranch.java @@ -0,0 +1,348 @@ +/* + * + * 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 java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ScheduledFuture; + +import org.apache.log4j.Logger; +import org.apache.qpid.AMQStoreException; +import org.apache.qpid.server.message.EnqueableMessage; +import org.apache.qpid.server.protocol.AMQSessionModel; +import org.apache.qpid.server.queue.BaseQueue; +import org.apache.qpid.server.store.MessageStore; +import org.apache.qpid.server.virtualhost.VirtualHost; +import org.apache.qpid.transport.Xid; + +public class DtxBranch +{ + private static final Logger _logger = Logger.getLogger(DtxBranch.class); + + private final Xid _xid; + private final List _postTransactionActions = new ArrayList(); + private State _state = State.ACTIVE; + private long _timeout; + private Map _associatedSessions = new HashMap(); + private final List _enqueueRecords = new ArrayList(); + private final List _dequeueRecords = new ArrayList(); + + private MessageStore.Transaction _transaction; + private long _expiration; + private VirtualHost _vhost; + private ScheduledFuture _timeoutFuture; + private MessageStore _store; + + + public enum State + { + ACTIVE, + PREPARED, + TIMEDOUT, + SUSPENDED, + FORGOTTEN, + HEUR_COM, + HEUR_RB, + ROLLBACK_ONLY + } + + + public DtxBranch(Xid xid, MessageStore store, VirtualHost vhost) + { + _xid = xid; + _store = store; + _vhost = vhost; + } + + public Xid getXid() + { + return _xid; + } + + public State getState() + { + return _state; + } + + public void setState(State state) + { + _state = state; + } + + public long getTimeout() + { + return _timeout; + } + + public void setTimeout(long timeout) + { + if(_timeoutFuture != null) + { + _timeoutFuture.cancel(false); + } + _timeout = timeout; + _expiration = timeout == 0 ? 0 : System.currentTimeMillis() + timeout; + + if(_timeout == 0) + { + _timeoutFuture = null; + } + else + { + _timeoutFuture = _vhost.scheduleTask(_timeout, new Runnable() + { + public void run() + { + setState(State.TIMEDOUT); + try + { + rollback(); + } + catch (AMQStoreException e) + { + _logger.error("Unexpected error when attempting to rollback XA transaction ("+ + _xid + ") due to timeout", e); + throw new RuntimeException(e); + } + } + }); + } + } + + public boolean expired() + { + return _timeout != 0 && _expiration < System.currentTimeMillis(); + } + + public synchronized boolean isAssociated(AMQSessionModel session) + { + return _associatedSessions.containsKey(session); + } + + public synchronized boolean hasAssociatedSessions() + { + return !_associatedSessions.isEmpty(); + } + + + public synchronized boolean hasAssociatedActiveSessions() + { + if(hasAssociatedSessions()) + { + for(State state : _associatedSessions.values()) + { + if(state != State.SUSPENDED) + { + return true; + } + } + } + return false; + } + + public synchronized void clearAssociations() + { + _associatedSessions.clear(); + } + + synchronized boolean associateSession(AMQSessionModel associatedSession) + { + return _associatedSessions.put(associatedSession, State.ACTIVE) != null; + } + + synchronized boolean disassociateSession(AMQSessionModel associatedSession) + { + return _associatedSessions.remove(associatedSession) != null; + } + + public synchronized boolean resumeSession(AMQSessionModel session) + { + if(_associatedSessions.containsKey(session) && _associatedSessions.get(session) == State.SUSPENDED) + { + _associatedSessions.put(session, State.ACTIVE); + return true; + } + return false; + } + + public synchronized boolean suspendSession(AMQSessionModel session) + { + if(_associatedSessions.containsKey(session) && _associatedSessions.get(session) == State.ACTIVE) + { + _associatedSessions.put(session, State.SUSPENDED); + return true; + } + return false; + } + + public void prepare() throws AMQStoreException + { + + MessageStore.Transaction txn = _store.newTransaction(); + txn.recordXid(_xid.getFormat(), + _xid.getGlobalId(), + _xid.getBranchId(), + _enqueueRecords.toArray(new Record[_enqueueRecords.size()]), + _dequeueRecords.toArray(new Record[_dequeueRecords.size()])); + txn.commitTran(); + + prePrepareTransaction(); + } + + public synchronized void rollback() throws AMQStoreException + { + if(_timeoutFuture != null) + { + _timeoutFuture.cancel(false); + _timeoutFuture = null; + } + + + if(_transaction != null) + { + // prepare has previously been called + + MessageStore.Transaction txn = _store.newTransaction(); + txn.removeXid(_xid.getFormat(), _xid.getGlobalId(), _xid.getBranchId()); + txn.commitTran(); + + _transaction.abortTran(); + } + + for(ServerTransaction.Action action : _postTransactionActions) + { + action.onRollback(); + } + _postTransactionActions.clear(); + } + + public void commit() throws AMQStoreException + { + if(_timeoutFuture != null) + { + _timeoutFuture.cancel(false); + _timeoutFuture = null; + } + + if(_transaction == null) + { + prePrepareTransaction(); + } + else + { + _transaction.removeXid(_xid.getFormat(), _xid.getGlobalId(), _xid.getBranchId()); + } + _transaction.commitTran(); + + for(ServerTransaction.Action action : _postTransactionActions) + { + action.postCommit(); + } + _postTransactionActions.clear(); + } + + public void prePrepareTransaction() throws AMQStoreException + { + _transaction = _store.newTransaction(); + + for(Record enqueue : _enqueueRecords) + { + if(enqueue.isDurable()) + { + _transaction.enqueueMessage(enqueue.getQueue(), enqueue.getMessage()); + } + } + + + for(Record enqueue : _dequeueRecords) + { + if(enqueue.isDurable()) + { + _transaction.dequeueMessage(enqueue.getQueue(), enqueue.getMessage()); + } + } + } + + + public void addPostTransactionAcion(ServerTransaction.Action postTransactionAction) + { + _postTransactionActions.add(postTransactionAction); + } + + + public void dequeue(BaseQueue queue, EnqueableMessage message) + { + _dequeueRecords.add(new Record(queue, message)); + } + + + public void enqueue(BaseQueue queue, EnqueableMessage message) + { + _enqueueRecords.add(new Record(queue, message)); + } + + private static final class Record implements MessageStore.Transaction.Record + { + private final BaseQueue _queue; + private final EnqueableMessage _message; + + public Record(BaseQueue queue, EnqueableMessage message) + { + _queue = queue; + _message = message; + } + + public BaseQueue getQueue() + { + return _queue; + } + + public EnqueableMessage getMessage() + { + return _message; + } + + public boolean isDurable() + { + return _message.isPersistent() && _queue.isDurable(); + } + } + + + public void close() + { + if(_transaction != null) + { + try + { + _state = null; + _transaction.abortTran(); + } + catch(AMQStoreException e) + { + _logger.error("Error while closing XA branch", e); + } + } + } +} diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/DtxException.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/DtxException.java new file mode 100644 index 0000000000..d18d0cb68b --- /dev/null +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/DtxException.java @@ -0,0 +1,44 @@ +/* + * + * 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; + +public class DtxException extends Exception +{ + public DtxException() + { + } + + public DtxException(String message) + { + super(message); + } + + public DtxException(String message, Throwable cause) + { + super(message, cause); + } + + public DtxException(Throwable cause) + { + super(cause); + } +} diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/DtxNotSelectedException.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/DtxNotSelectedException.java new file mode 100644 index 0000000000..c1289b1fdd --- /dev/null +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/DtxNotSelectedException.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.server.txn; + +public class DtxNotSelectedException extends DtxException +{ + public DtxNotSelectedException() + { + super("Distribution transactions have not been selected on this session"); + } +} diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/DtxRegistry.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/DtxRegistry.java new file mode 100644 index 0000000000..5c54c1164f --- /dev/null +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/DtxRegistry.java @@ -0,0 +1,333 @@ +/* + * + * 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 java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.apache.qpid.AMQStoreException; +import org.apache.qpid.server.protocol.AMQSessionModel; +import org.apache.qpid.transport.Xid; + +public class DtxRegistry +{ + private final Map _branches = new HashMap(); + + + private static final class ComparableXid + { + private final Xid _xid; + + private ComparableXid(Xid xid) + { + _xid = xid; + } + + @Override + public boolean equals(Object o) + { + if(this == o) + { + return true; + } + if(o == null || getClass() != o.getClass()) + { + return false; + } + + ComparableXid that = (ComparableXid) o; + + return compareBytes(_xid.getBranchId(), that._xid.getBranchId()) + && compareBytes(_xid.getGlobalId(), that._xid.getGlobalId()); + } + + private static boolean compareBytes(byte[] a, byte[] b) + { + if(a.length != b.length) + { + return false; + } + for(int i = 0; i < a.length; i++) + { + if(a[i] != b[i]) + { + return false; + } + } + return true; + } + + + @Override + public int hashCode() + { + int result = 0; + for(int i = 0; i < _xid.getGlobalId().length; i++) + { + result = 31 * result + (int) _xid.getGlobalId()[i]; + } + for(int i = 0; i < _xid.getBranchId().length; i++) + { + result = 31 * result + (int) _xid.getBranchId()[i]; + } + + return result; + } + } + + public synchronized DtxBranch getBranch(Xid xid) + { + return _branches.get(new ComparableXid(xid)); + } + + public synchronized boolean registerBranch(DtxBranch branch) + { + ComparableXid xid = new ComparableXid(branch.getXid()); + if(!_branches.containsKey(xid)) + { + _branches.put(xid, branch); + return true; + } + return false; + } + + synchronized boolean unregisterBranch(DtxBranch branch) + { + return (_branches.remove(new ComparableXid(branch.getXid())) != null); + } + + public void commit(Xid id, boolean onePhase) + throws IncorrectDtxStateException, UnknownDtxBranchException, AMQStoreException, RollbackOnlyDtxException, TimeoutDtxException + { + DtxBranch branch = getBranch(id); + if(branch != null) + { + synchronized (branch) + { + if(!branch.hasAssociatedActiveSessions()) + { + branch.clearAssociations(); + + if(branch.expired() || branch.getState() == DtxBranch.State.TIMEDOUT) + { + unregisterBranch(branch); + throw new TimeoutDtxException(id); + } + else if(branch.getState() == DtxBranch.State.ROLLBACK_ONLY) + { + throw new RollbackOnlyDtxException(id); + } + else if(onePhase && branch.getState() == DtxBranch.State.PREPARED) + { + throw new IncorrectDtxStateException("Cannot call one-phase commit on a prepared branch", id); + } + else if(!onePhase && branch.getState() != DtxBranch.State.PREPARED) + { + throw new IncorrectDtxStateException("Cannot call two-phase commit on a non-prepared branch", + id); + } + branch.commit(); + branch.setState(DtxBranch.State.FORGOTTEN); + unregisterBranch(branch); + } + else + { + throw new IncorrectDtxStateException("Branch was still associated with a session", id); + } + } + } + else + { + throw new UnknownDtxBranchException(id); + } + } + + public synchronized void prepare(Xid id) + throws UnknownDtxBranchException, + IncorrectDtxStateException, AMQStoreException, RollbackOnlyDtxException, TimeoutDtxException + { + DtxBranch branch = getBranch(id); + if(branch != null) + { + synchronized (branch) + { + if(!branch.hasAssociatedActiveSessions()) + { + branch.clearAssociations(); + + if(branch.expired() || branch.getState() == DtxBranch.State.TIMEDOUT) + { + unregisterBranch(branch); + throw new TimeoutDtxException(id); + } + else if(branch.getState() != DtxBranch.State.ACTIVE + && branch.getState() != DtxBranch.State.ROLLBACK_ONLY) + { + throw new IncorrectDtxStateException("Cannot prepare a transaction in state " + + branch.getState(), id); + } + else + { + branch.prepare(); + branch.setState(DtxBranch.State.PREPARED); + } + } + else + { + throw new IncorrectDtxStateException("Branch still has associated sessions", id); + } + } + } + else + { + throw new UnknownDtxBranchException(id); + } + } + + public void rollback(Xid id) + throws IncorrectDtxStateException, + UnknownDtxBranchException, + AMQStoreException, TimeoutDtxException + { + + DtxBranch branch = getBranch(id); + if(branch != null) + { + synchronized (branch) + { + if(branch.expired() || branch.getState() == DtxBranch.State.TIMEDOUT) + { + unregisterBranch(branch); + throw new TimeoutDtxException(id); + } + if(!branch.hasAssociatedActiveSessions()) + { + branch.clearAssociations(); + branch.rollback(); + branch.setState(DtxBranch.State.FORGOTTEN); + unregisterBranch(branch); + } + else + { + throw new IncorrectDtxStateException("Branch was still associated with a session", id); + } + } + } + else + { + throw new UnknownDtxBranchException(id); + } + } + + + public void forget(Xid id) throws UnknownDtxBranchException, IncorrectDtxStateException + { + DtxBranch branch = getBranch(id); + if(branch != null) + { + synchronized (branch) + { + if(!branch.hasAssociatedSessions()) + { + if(branch.getState() != DtxBranch.State.HEUR_COM && branch.getState() != DtxBranch.State.HEUR_RB) + { + throw new IncorrectDtxStateException("Branch should not be forgotten - " + + "it is not heuristically complete", id); + } + branch.setState(DtxBranch.State.FORGOTTEN); + unregisterBranch(branch); + } + else + { + throw new IncorrectDtxStateException("Branch was still associated with a session", id); + } + } + } + else + { + throw new UnknownDtxBranchException(id); + } + } + + public long getTimeout(Xid id) throws UnknownDtxBranchException + { + DtxBranch branch = getBranch(id); + if(branch != null) + { + return branch.getTimeout(); + } + else + { + throw new UnknownDtxBranchException(id); + } + } + + public void setTimeout(Xid id, long timeout) throws UnknownDtxBranchException + { + DtxBranch branch = getBranch(id); + if(branch != null) + { + branch.setTimeout(timeout); + } + else + { + throw new UnknownDtxBranchException(id); + } + } + + public synchronized List recover() + { + List inDoubt = new ArrayList(); + for(DtxBranch branch : _branches.values()) + { + if(branch.getState() == DtxBranch.State.PREPARED) + { + inDoubt.add(branch.getXid()); + } + } + return inDoubt; + } + + public synchronized void endAssociations(AMQSessionModel session) + { + for(DtxBranch branch : _branches.values()) + { + if(branch.isAssociated(session)) + { + branch.setState(DtxBranch.State.ROLLBACK_ONLY); + branch.disassociateSession(session); + } + } + } + + + public synchronized void close() + { + for(DtxBranch branch : _branches.values()) + { + branch.close(); + } + _branches.clear(); + } + +} diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/IncorrectDtxStateException.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/IncorrectDtxStateException.java new file mode 100644 index 0000000000..45f094e4b9 --- /dev/null +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/IncorrectDtxStateException.java @@ -0,0 +1,32 @@ +/* + * + * 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.transport.Xid; + +public class IncorrectDtxStateException extends DtxException +{ + public IncorrectDtxStateException(String message, Xid id) + { + super(message + " (xid: " + id + ")"); + } +} diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/JoinAndResumeDtxException.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/JoinAndResumeDtxException.java new file mode 100644 index 0000000000..a25e5a4ed6 --- /dev/null +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/JoinAndResumeDtxException.java @@ -0,0 +1,32 @@ +/* + * + * 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.transport.Xid; + +public class JoinAndResumeDtxException extends DtxException +{ + public JoinAndResumeDtxException(Xid id) + { + super("Cannot start a branch with both join and resume set " + id); + } +} diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/LocalTransaction.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/LocalTransaction.java index 34bac0411e..9b61f7543f 100755 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/LocalTransaction.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/LocalTransaction.java @@ -20,9 +20,8 @@ package org.apache.qpid.server.txn; * */ -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.apache.qpid.AMQException; import org.apache.qpid.server.message.EnqueableMessage; @@ -31,8 +30,9 @@ import org.apache.qpid.server.queue.BaseQueue; import org.apache.qpid.server.queue.QueueEntry; import org.apache.qpid.server.store.MessageStore; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; /** * A concrete implementation of ServerTransaction where enqueue/dequeue diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/NotAssociatedDtxException.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/NotAssociatedDtxException.java new file mode 100644 index 0000000000..de070546a7 --- /dev/null +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/NotAssociatedDtxException.java @@ -0,0 +1,32 @@ +/* + * + * 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.transport.Xid; + +public class NotAssociatedDtxException extends DtxException +{ + public NotAssociatedDtxException(Xid id) + { + super("Xid " + id + " not associated with the current session"); + } +} diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/RollbackOnlyDtxException.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/RollbackOnlyDtxException.java new file mode 100644 index 0000000000..6cf12d8631 --- /dev/null +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/RollbackOnlyDtxException.java @@ -0,0 +1,32 @@ +/* + * + * 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.transport.Xid; + +public class RollbackOnlyDtxException extends DtxException +{ + public RollbackOnlyDtxException(Xid id) + { + super("Transaction " + id + " may only be rolled back"); + } +} diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/SuspendAndFailDtxException.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/SuspendAndFailDtxException.java new file mode 100644 index 0000000000..228844fd63 --- /dev/null +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/SuspendAndFailDtxException.java @@ -0,0 +1,32 @@ +/* + * + * 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.transport.Xid; + +public class SuspendAndFailDtxException extends DtxException +{ +public SuspendAndFailDtxException(Xid id) +{ + super("Cannot end a branch with both suspend and fail set " + id); +} +} diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/TimeoutDtxException.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/TimeoutDtxException.java new file mode 100644 index 0000000000..50f7708d8a --- /dev/null +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/TimeoutDtxException.java @@ -0,0 +1,32 @@ +/* + * + * 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.transport.Xid; + +public class TimeoutDtxException extends DtxException +{ + public TimeoutDtxException(Xid id) + { + super("Transaction " + id + " has timed-out and may only be rolled back"); + } +} diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/UnknownDtxBranchException.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/UnknownDtxBranchException.java new file mode 100644 index 0000000000..c23e518365 --- /dev/null +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/UnknownDtxBranchException.java @@ -0,0 +1,32 @@ +/* + * + * 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.transport.Xid; + +public class UnknownDtxBranchException extends DtxException +{ + public UnknownDtxBranchException(Xid id) + { + super("Unknown xid " + id); + } +} diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/util/CircularBuffer.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/util/CircularBuffer.java deleted file mode 100644 index e730e2f3c3..0000000000 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/util/CircularBuffer.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.server.util; - -import java.util.Iterator; - -import org.apache.log4j.Logger; - -public class CircularBuffer implements Iterable -{ - - private static final Logger _logger = Logger.getLogger(CircularBuffer.class); - - private final Object[] _log; - private int _size; - private int _index; - - public CircularBuffer(int size) - { - _log = new Object[size]; - } - - public void add(Object o) - { - _log[_index++] = o; - _size = Math.min(_size+1, _log.length); - if(_index >= _log.length) - { - _index = 0; - } - } - - public Object get(int i) - { - if(i >= _log.length) - { - throw new ArrayIndexOutOfBoundsException(i); - } - return _log[index(i)]; - } - - public int size() { - return _size; - } - - public Iterator iterator() - { - return new Iterator() - { - private int i = 0; - - public boolean hasNext() - { - return i < _size; - } - - public Object next() - { - return get(i++); - } - - public void remove() - { - throw new UnsupportedOperationException(); - } - }; - } - - public String toString() - { - StringBuilder s = new StringBuilder(); - boolean first = true; - for(Object o : this) - { - if(!first) - { - s.append(", "); - } - else - { - first = false; - } - s.append(o); - } - return s.toString(); - } - - public void dump() - { - for(Object o : this) - { - _logger.info(o); - } - } - - int index(int i) - { - return _size == _log.length ? (_index + i) % _log.length : i; - } - - public static void main(String[] artgv) - { - String[] items = new String[]{ - "A","B","C","D","E","F","G","H","I","J","K" - }; - CircularBuffer buffer = new CircularBuffer(5); - for(String s : items) - { - buffer.add(s); - _logger.info(buffer); - } - } -} diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/util/LoggingProxy.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/util/LoggingProxy.java deleted file mode 100644 index eda97e0ed2..0000000000 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/util/LoggingProxy.java +++ /dev/null @@ -1,105 +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.util; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.util.Arrays; - -/** - * Dynamic proxy that records invocations in a fixed size circular buffer, - * dumping details on hitting an exception. - *

- * Useful in debugging. - *

- */ -public class LoggingProxy implements InvocationHandler -{ - private final Object _target; - private final CircularBuffer _log; - - public LoggingProxy(Object target, int size) - { - _target = target; - _log = new CircularBuffer(size); - } - - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable - { - try - { - entered(method, args); - Object result = method.invoke(_target, args); - returned(method, result); - return result; - } - catch(InvocationTargetException e) - { - dump(); - throw e.getTargetException(); - } - } - - void dump() - { - _log.dump(); - } - - CircularBuffer getBuffer() - { - return _log; - } - - private synchronized void entered(Method method, Object[] args) - { - if (args == null) - { - _log.add(Thread.currentThread() + ": " + method.getName() + "() entered"); - } - else - { - _log.add(Thread.currentThread() + ": " + method.getName() + "(" + Arrays.toString(args) + ") entered"); - } - } - - private synchronized void returned(Method method, Object result) - { - if (method.getReturnType() == Void.TYPE) - { - _log.add(Thread.currentThread() + ": " + method.getName() + "() returned"); - } - else - { - _log.add(Thread.currentThread() + ": " + method.getName() + "() returned " + result); - } - } - - public Object getProxy(Class... c) - { - return Proxy.newProxyInstance(_target.getClass().getClassLoader(), c, this); - } - - public int getBufferSize() { - return _log.size(); - } -} diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/HouseKeepingTask.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/HouseKeepingTask.java index ebace95f65..523bafb8e1 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/HouseKeepingTask.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/HouseKeepingTask.java @@ -21,13 +21,14 @@ package org.apache.qpid.server.virtualhost; import org.apache.log4j.Logger; + import org.apache.qpid.server.logging.RootMessageLogger; import org.apache.qpid.server.logging.actors.AbstractActor; import org.apache.qpid.server.logging.actors.CurrentActor; public abstract class HouseKeepingTask implements Runnable { - Logger _logger = Logger.getLogger(this.getClass()); + private Logger _logger = Logger.getLogger(this.getClass()); private VirtualHost _virtualHost; @@ -59,7 +60,7 @@ public abstract class HouseKeepingTask implements Runnable { execute(); } - catch (Throwable e) + catch (Exception e) { _logger.warn(this.getClass().getSimpleName() + " throw exception: " + e, e); } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/ManagedVirtualHost.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/ManagedVirtualHost.java index 767474d5ae..cb7f213f06 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/ManagedVirtualHost.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/ManagedVirtualHost.java @@ -20,10 +20,10 @@ */ package org.apache.qpid.server.virtualhost; -import java.io.IOException; - import org.apache.qpid.management.common.mbeans.annotations.MBeanAttribute; +import java.io.IOException; + /** * The management interface exposed to allow management of a virtualHost */ diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHost.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHost.java index 41a5471a64..4b586db628 100755 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHost.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHost.java @@ -22,7 +22,7 @@ package org.apache.qpid.server.virtualhost; import java.util.Map; import java.util.UUID; - +import java.util.concurrent.ScheduledFuture; import org.apache.qpid.common.Closeable; import org.apache.qpid.server.binding.BindingFactory; import org.apache.qpid.server.configuration.ConfigStore; @@ -37,10 +37,10 @@ import org.apache.qpid.server.protocol.v1_0.LinkRegistry; import org.apache.qpid.server.queue.QueueRegistry; import org.apache.qpid.server.registry.IApplicationRegistry; import org.apache.qpid.server.security.SecurityManager; -import org.apache.qpid.server.security.auth.manager.AuthenticationManager; import org.apache.qpid.server.stats.StatisticsGatherer; import org.apache.qpid.server.store.DurableConfigurationStore; import org.apache.qpid.server.store.MessageStore; +import org.apache.qpid.server.txn.DtxRegistry; public interface VirtualHost extends DurableConfigurationStore.Source, VirtualHostConfig, Closeable, StatisticsGatherer { @@ -60,8 +60,6 @@ public interface VirtualHost extends DurableConfigurationStore.Source, VirtualHo DurableConfigurationStore getDurableConfigurationStore(); - AuthenticationManager getAuthenticationManager(); - SecurityManager getSecurityManager(); void close(); @@ -97,7 +95,11 @@ public interface VirtualHost extends DurableConfigurationStore.Source, VirtualHo ConfigStore getConfigStore(); + DtxRegistry getDtxRegistry(); + void removeBrokerConnection(BrokerLink brokerLink); LinkRegistry getLinkRegistry(String remoteContainerId); + + ScheduledFuture scheduleTask(long delay, Runnable timeoutTask); } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHostConfigRecoveryHandler.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHostConfigRecoveryHandler.java index 51892d965a..0e965472d5 100755 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHostConfigRecoveryHandler.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHostConfigRecoveryHandler.java @@ -20,43 +20,47 @@ */ package org.apache.qpid.server.virtualhost; +import java.io.DataInputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.UUID; +import org.apache.log4j.Logger; +import org.apache.qpid.AMQException; +import org.apache.qpid.AMQStoreException; +import org.apache.qpid.framing.AMQShortString; +import org.apache.qpid.framing.FieldTable; +import org.apache.qpid.server.binding.BindingFactory; +import org.apache.qpid.server.exchange.Exchange; import org.apache.qpid.server.federation.BrokerLink; +import org.apache.qpid.server.logging.actors.CurrentActor; +import org.apache.qpid.server.logging.messages.TransactionLogMessages; +import org.apache.qpid.server.logging.subjects.MessageStoreLogSubject; +import org.apache.qpid.server.message.AMQMessage; +import org.apache.qpid.server.message.AbstractServerMessageImpl; import org.apache.qpid.server.message.EnqueableMessage; +import org.apache.qpid.server.message.MessageTransferMessage; +import org.apache.qpid.server.message.ServerMessage; +import org.apache.qpid.server.queue.AMQQueue; +import org.apache.qpid.server.queue.AMQQueueFactory; +import org.apache.qpid.server.queue.QueueEntry; import org.apache.qpid.server.store.ConfigurationRecoveryHandler; import org.apache.qpid.server.store.MessageStore; import org.apache.qpid.server.store.MessageStoreRecoveryHandler; import org.apache.qpid.server.store.StoredMessage; import org.apache.qpid.server.store.TransactionLogRecoveryHandler; import org.apache.qpid.server.store.TransactionLogResource; -import org.apache.qpid.server.queue.AMQQueue; -import org.apache.qpid.server.queue.AMQQueueFactory; -import org.apache.qpid.server.queue.QueueRegistry; -import org.apache.qpid.server.exchange.Exchange; -import org.apache.qpid.server.logging.subjects.MessageStoreLogSubject; -import org.apache.qpid.server.logging.actors.CurrentActor; -import org.apache.qpid.server.logging.messages.TransactionLogMessages; -import org.apache.qpid.server.message.AMQMessage; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.message.MessageTransferMessage; -import org.apache.qpid.server.binding.BindingFactory; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.AMQException; - -import org.apache.log4j.Logger; +import org.apache.qpid.server.txn.DtxBranch; +import org.apache.qpid.server.txn.DtxRegistry; +import org.apache.qpid.server.txn.ServerTransaction; +import org.apache.qpid.transport.Xid; +import org.apache.qpid.transport.util.Functions; import org.apache.qpid.util.ByteBufferInputStream; -import java.io.DataInputStream; -import java.io.IOException; -import java.nio.ByteBuffer; - -import java.util.List; -import java.util.ArrayList; -import java.util.Map; -import java.util.HashMap; -import java.util.TreeMap; -import java.util.UUID; - public class VirtualHostConfigRecoveryHandler implements ConfigurationRecoveryHandler, ConfigurationRecoveryHandler.QueueRecoveryHandler, ConfigurationRecoveryHandler.ExchangeRecoveryHandler, @@ -65,7 +69,8 @@ public class VirtualHostConfigRecoveryHandler implements ConfigurationRecoveryHa MessageStoreRecoveryHandler, MessageStoreRecoveryHandler.StoredMessageRecoveryHandler, TransactionLogRecoveryHandler, - TransactionLogRecoveryHandler.QueueEntryRecoveryHandler + TransactionLogRecoveryHandler.QueueEntryRecoveryHandler, + TransactionLogRecoveryHandler.DtxRecordRecoveryHandler { private static final Logger _logger = Logger.getLogger(VirtualHostConfigRecoveryHandler.class); @@ -78,7 +83,7 @@ public class VirtualHostConfigRecoveryHandler implements ConfigurationRecoveryHa private MessageStore _store; private final Map _queueRecoveries = new TreeMap(); - private Map _recoveredMessages = new HashMap(); + private Map _recoveredMessages = new HashMap(); private Map _unusedMessages = new HashMap(); @@ -160,7 +165,7 @@ public class VirtualHostConfigRecoveryHandler implements ConfigurationRecoveryHa public void message(StoredMessage message) { - ServerMessage serverMessage; + AbstractServerMessageImpl serverMessage; switch(message.getMetaData().getType()) { case META_DATA_0_8: @@ -173,9 +178,6 @@ public class VirtualHostConfigRecoveryHandler implements ConfigurationRecoveryHa throw new RuntimeException("Unknown message type retrieved from store " + message.getMetaData().getClass()); } - //_logger.debug("Recovered message with id " + serverMessage); - - _recoveredMessages.put(message.getMessageNumber(), serverMessage); _unusedMessages.put(message.getMessageNumber(), message); } @@ -198,6 +200,164 @@ public class VirtualHostConfigRecoveryHandler implements ConfigurationRecoveryHa { } + public void dtxRecord(long format, byte[] globalId, byte[] branchId, + MessageStore.Transaction.Record[] enqueues, + MessageStore.Transaction.Record[] dequeues) + { + Xid id = new Xid(format, globalId, branchId); + DtxRegistry dtxRegistry = _virtualHost.getDtxRegistry(); + DtxBranch branch = dtxRegistry.getBranch(id); + if(branch == null) + { + branch = new DtxBranch(id, _store, _virtualHost); + dtxRegistry.registerBranch(branch); + } + for(MessageStore.Transaction.Record record : enqueues) + { + final AMQQueue queue = _virtualHost.getQueueRegistry().getQueue(record.getQueue().getResourceName()); + if(queue != null) + { + final long messageId = record.getMessage().getMessageNumber(); + final AbstractServerMessageImpl message = _recoveredMessages.get(messageId); + _unusedMessages.remove(messageId); + + if(message != null) + { + message.incrementReference(); + + branch.enqueue(queue,message); + + branch.addPostTransactionAcion(new ServerTransaction.Action() + { + + public void postCommit() + { + try + { + + queue.enqueue(message, true, null); + message.decrementReference(); + } + catch (AMQException e) + { + _logger.error("Unable to enqueue message " + message.getMessageNumber() + " into " + + "queue " + queue.getName() + " (from XA transaction)", e); + throw new RuntimeException(e); + } + } + + public void onRollback() + { + message.decrementReference(); + } + }); + } + else + { + StringBuilder xidString = xidAsString(id); + String messageNumberString = String.valueOf(message.getMessageNumber()); + CurrentActor.get().message(_logSubject, + TransactionLogMessages.XA_INCOMPLETE_MESSAGE(xidString.toString(), + messageNumberString)); + + } + + } + else + { + StringBuilder xidString = xidAsString(id); + CurrentActor.get().message(_logSubject, + TransactionLogMessages.XA_INCOMPLETE_QUEUE(xidString.toString(), + record.getQueue().getResourceName())); + + } + } + for(MessageStore.Transaction.Record record : dequeues) + { + final AMQQueue queue = _virtualHost.getQueueRegistry().getQueue(record.getQueue().getResourceName()); + if(queue != null) + { + final long messageId = record.getMessage().getMessageNumber(); + final AbstractServerMessageImpl message = _recoveredMessages.get(messageId); + _unusedMessages.remove(messageId); + + if(message != null) + { + final QueueEntry entry = queue.getMessageOnTheQueue(messageId); + + entry.acquire(); + + branch.dequeue(queue, message); + + branch.addPostTransactionAcion(new ServerTransaction.Action() + { + + public void postCommit() + { + entry.discard(); + } + + public void onRollback() + { + entry.release(); + } + }); + } + else + { + StringBuilder xidString = xidAsString(id); + String messageNumberString = String.valueOf(message.getMessageNumber()); + CurrentActor.get().message(_logSubject, + TransactionLogMessages.XA_INCOMPLETE_MESSAGE(xidString.toString(), + messageNumberString)); + + } + + } + else + { + StringBuilder xidString = xidAsString(id); + CurrentActor.get().message(_logSubject, + TransactionLogMessages.XA_INCOMPLETE_QUEUE(xidString.toString(), + queue.getName())); + } + + } + + try + { + branch.setState(DtxBranch.State.PREPARED); + branch.prePrepareTransaction(); + } + catch (AMQStoreException e) + { + _logger.error("Unexpected database exception when attempting to prepare a recovered XA transaction " + + xidAsString(id), e); + throw new RuntimeException(e); + } + } + + private static StringBuilder xidAsString(Xid id) + { + return new StringBuilder("(") + .append(id.getFormat()) + .append(',') + .append(Functions.str(id.getGlobalId())) + .append(',') + .append(Functions.str(id.getBranchId())) + .append(')'); + } + + public void completeDtxRecordRecovery() + { + for(StoredMessage m : _unusedMessages.values()) + { + _logger.warn("Message id " + m.getMessageNumber() + " in store, but not in any queue - removing...."); + m.remove(); + } + CurrentActor.get().message(_logSubject, TransactionLogMessages.RECOVERY_COMPLETE(null, false)); + } + private static final class ProcessAction { private final AMQQueue _queue; @@ -354,15 +514,9 @@ public class VirtualHostConfigRecoveryHandler implements ConfigurationRecoveryHa } - public void completeQueueEntryRecovery() + public DtxRecordRecoveryHandler completeQueueEntryRecovery() { - for(StoredMessage m : _unusedMessages.values()) - { - _logger.warn("Message id " + m.getMessageNumber() + " in store, but not in any queue - removing...."); - m.remove(); - } - for(Map.Entry entry : _queueRecoveries.entrySet()) { CurrentActor.get().message(_logSubject, TransactionLogMessages.RECOVERED(entry.getValue(), entry.getKey())); @@ -370,7 +524,9 @@ public class VirtualHostConfigRecoveryHandler implements ConfigurationRecoveryHa CurrentActor.get().message(_logSubject, TransactionLogMessages.RECOVERY_COMPLETE(entry.getKey(), true)); } - CurrentActor.get().message(_logSubject, TransactionLogMessages.RECOVERY_COMPLETE(null, false)); + + + return this; } private static class DummyMessage implements EnqueableMessage diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHostImpl.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHostImpl.java index a4a3633af7..9a0606f47a 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHostImpl.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHostImpl.java @@ -20,21 +20,11 @@ */ package org.apache.qpid.server.virtualhost; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -import javax.management.NotCompliantMBeanException; -import javax.management.ObjectName; - +import java.util.concurrent.ScheduledFuture; import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.ConfigurationException; import org.apache.log4j.Logger; + import org.apache.qpid.AMQException; import org.apache.qpid.AMQStoreException; import org.apache.qpid.framing.AMQShortString; @@ -73,14 +63,25 @@ 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.SecurityManager; -import org.apache.qpid.server.security.auth.manager.AuthenticationManager; import org.apache.qpid.server.stats.StatisticsCounter; import org.apache.qpid.server.store.ConfigurationRecoveryHandler; import org.apache.qpid.server.store.DurableConfigurationStore; import org.apache.qpid.server.store.MessageStore; +import org.apache.qpid.server.txn.DtxRegistry; import org.apache.qpid.server.virtualhost.plugins.VirtualHostPlugin; import org.apache.qpid.server.virtualhost.plugins.VirtualHostPluginFactory; +import javax.management.NotCompliantMBeanException; +import javax.management.ObjectName; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + public class VirtualHostImpl implements VirtualHost { private static final Logger _logger = Logger.getLogger(VirtualHostImpl.class); @@ -97,11 +98,11 @@ public class VirtualHostImpl implements VirtualHost private MessageStore _messageStore; - protected VirtualHostMBean _virtualHostMBean; + private DtxRegistry _dtxRegistry; - private AMQBrokerManagerMBean _brokerMBean; + private VirtualHostMBean _virtualHostMBean; - private final AuthenticationManager _authenticationManager; + private AMQBrokerManagerMBean _brokerMBean; private SecurityManager _securityManager; @@ -121,6 +122,7 @@ public class VirtualHostImpl implements VirtualHost private static final int HOUSEKEEPING_SHUTDOWN_TIMEOUT = 5; private final Map _linkRegistry = new HashMap(); + public IConnectionRegistry getConnectionRegistry() { return _connectionRegistry; @@ -191,6 +193,7 @@ public class VirtualHostImpl implements VirtualHost _broker = _appRegistry.getBroker(); _configuration = hostConfig; _name = _configuration.getName(); + _dtxRegistry = new DtxRegistry(); _id = _appRegistry.getConfigStore().createId(); @@ -241,7 +244,6 @@ public class VirtualHostImpl implements VirtualHost initialiseMessageStore(hostConfig); } - _authenticationManager = ApplicationRegistry.getInstance().getAuthenticationManager(); _brokerMBean = new AMQBrokerManagerMBean(_virtualHostMBean); _brokerMBean.register(); @@ -260,54 +262,9 @@ public class VirtualHostImpl implements VirtualHost { if (period != 0L) { - class VirtualHostHouseKeepingTask extends HouseKeepingTask - { - public VirtualHostHouseKeepingTask(VirtualHost vhost) - { - super(vhost); - } - public void execute() - { - for (AMQQueue q : _queueRegistry.getQueues()) - { - _logger.debug("Checking message status for queue: " - + q.getName()); - try - { - q.checkMessageStatus(); - } - catch (Exception e) - { - _logger.error("Exception in housekeeping for queue: " - + q.getNameShortString().toString(), e); - //Don't throw exceptions as this will stop the - // house keeping task from running. - } - } - for (AMQConnectionModel connection : getConnectionRegistry().getConnections()) - { - _logger.debug("Checking for long running open transactions on connection " + connection); - for (AMQSessionModel session : connection.getSessionModels()) - { - _logger.debug("Checking for long running open transactions on session " + session); - try - { - session.checkTransactionStatus(_configuration.getTransactionTimeoutOpenWarn(), - _configuration.getTransactionTimeoutOpenClose(), - _configuration.getTransactionTimeoutIdleWarn(), - _configuration.getTransactionTimeoutIdleClose()); - } - catch (Exception e) - { - _logger.error("Exception in housekeeping for connection: " + connection.toString(), e); - } - } - } - } - } - scheduleHouseKeepingTask(period, new VirtualHostHouseKeepingTask(this)); + scheduleHouseKeepingTask(period, new VirtualHostHouseKeepingTask()); Map plugins = ApplicationRegistry.getInstance().getPluginManager().getVirtualHostPlugins(); @@ -340,6 +297,53 @@ public class VirtualHostImpl implements VirtualHost } } + private class VirtualHostHouseKeepingTask extends HouseKeepingTask + { + public VirtualHostHouseKeepingTask() + { + super(VirtualHostImpl.this); + } + + public void execute() + { + for (AMQQueue q : _queueRegistry.getQueues()) + { + _logger.debug("Checking message status for queue: " + + q.getName()); + try + { + q.checkMessageStatus(); + } + catch (Exception e) + { + _logger.error("Exception in housekeeping for queue: " + + q.getNameShortString().toString(), e); + //Don't throw exceptions as this will stop the + // house keeping task from running. + } + } + for (AMQConnectionModel connection : getConnectionRegistry().getConnections()) + { + _logger.debug("Checking for long running open transactions on connection " + connection); + for (AMQSessionModel session : connection.getSessionModels()) + { + _logger.debug("Checking for long running open transactions on session " + session); + try + { + session.checkTransactionStatus(_configuration.getTransactionTimeoutOpenWarn(), + _configuration.getTransactionTimeoutOpenClose(), + _configuration.getTransactionTimeoutIdleWarn(), + _configuration.getTransactionTimeoutIdleClose()); + } + catch (Exception e) + { + _logger.error("Exception in housekeeping for connection: " + connection.toString(), e); + } + } + } + } + } + /** * Allow other broker components to register a HouseKeepingTask * @@ -352,6 +356,11 @@ public class VirtualHostImpl implements VirtualHost TimeUnit.MILLISECONDS); } + public ScheduledFuture scheduleTask(long delay, Runnable task) + { + return _houseKeepingTasks.schedule(task, delay, TimeUnit.MILLISECONDS); + } + public long getHouseKeepingTaskCount() { return _houseKeepingTasks.getTaskCount(); @@ -575,11 +584,6 @@ public class VirtualHostImpl implements VirtualHost return _durableConfigurationStore; } - public AuthenticationManager getAuthenticationManager() - { - return _authenticationManager; - } - public SecurityManager getSecurityManager() { return _securityManager; @@ -618,6 +622,11 @@ public class VirtualHostImpl implements VirtualHost } } + if(_dtxRegistry != null) + { + _dtxRegistry.close(); + } + //Close MessageStore if (_messageStore != null) { @@ -796,6 +805,11 @@ public class VirtualHostImpl implements VirtualHost return getApplicationRegistry().getConfigStore(); } + public DtxRegistry getDtxRegistry() + { + return _dtxRegistry; + } + /** * Temporary Startup RT class to record the creation of persistent queues / exchanges. * @@ -805,11 +819,11 @@ public class VirtualHostImpl implements VirtualHost */ private static class StartupRoutingTable implements DurableConfigurationStore { - public List exchange = new LinkedList(); - public List queue = new LinkedList(); - public List bindings = new LinkedList(); - public List links = new LinkedList(); - public List bridges = new LinkedList(); + private List exchange = new LinkedList(); + private List queue = new LinkedList(); + private List bindings = new LinkedList(); + private List links = new LinkedList(); + private List bridges = new LinkedList(); public void configure(VirtualHost virtualHost, String base, VirtualHostConfiguration config) throws Exception { @@ -876,8 +890,8 @@ public class VirtualHostImpl implements VirtualHost private static class CreateQueueTuple { - public AMQQueue queue; - public FieldTable arguments; + private AMQQueue queue; + private FieldTable arguments; public CreateQueueTuple(AMQQueue queue, FieldTable arguments) { @@ -888,10 +902,10 @@ public class VirtualHostImpl implements VirtualHost private static class CreateBindingTuple { - public AMQQueue queue; - public FieldTable arguments; - public Exchange exchange; - public AMQShortString routingKey; + private AMQQueue queue; + private FieldTable arguments; + private Exchange exchange; + private AMQShortString routingKey; public CreateBindingTuple(Exchange exchange, AMQShortString routingKey, AMQQueue queue, FieldTable args) { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHostRegistry.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHostRegistry.java index 32d0c4c4d1..ef621a166a 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHostRegistry.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHostRegistry.java @@ -21,8 +21,8 @@ package org.apache.qpid.server.virtualhost; import org.apache.qpid.common.Closeable; -import org.apache.qpid.server.registry.ApplicationRegistry; import org.apache.qpid.server.configuration.ConfigStore; +import org.apache.qpid.server.registry.ApplicationRegistry; import java.util.ArrayList; import java.util.Collection; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/ConfiguredQueueBindingListener.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/ConfiguredQueueBindingListener.java index 12206013eb..12886f400a 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/ConfiguredQueueBindingListener.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/ConfiguredQueueBindingListener.java @@ -20,19 +20,18 @@ */ package org.apache.qpid.server.virtualhost.plugins; -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - import org.apache.log4j.Logger; + import org.apache.qpid.server.binding.Binding; import org.apache.qpid.server.configuration.plugins.SlowConsumerDetectionQueueConfiguration; -import org.apache.qpid.server.exchange.AbstractExchange; import org.apache.qpid.server.exchange.Exchange; import org.apache.qpid.server.exchange.Exchange.BindingListener; import org.apache.qpid.server.queue.AMQQueue; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + /** * This is a listener that caches queues that are configured for slow consumer disconnection. * @@ -93,7 +92,7 @@ public class ConfiguredQueueBindingListener implements BindingListener /** * Lookup and return the cache of configured {@link AMQQueue}s. * - * Note that when accessing the cached queues, the {@link Iterator} is not thread safe + * Note that when accessing the cached queues, the {@link java.util.Iterator} is not thread safe * (see the {@link Collections#synchronizedSet(Set)} documentation) so a copy of the * cache is returned. * diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetection.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetection.java index 248b3b2143..2c6705bb3b 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetection.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetection.java @@ -19,21 +19,20 @@ */ package org.apache.qpid.server.virtualhost.plugins; -import java.util.Set; -import java.util.concurrent.TimeUnit; - import org.apache.qpid.framing.AMQShortString; +import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin; import org.apache.qpid.server.configuration.plugins.SlowConsumerDetectionConfiguration; import org.apache.qpid.server.configuration.plugins.SlowConsumerDetectionQueueConfiguration; -import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin; import org.apache.qpid.server.exchange.ExchangeRegistry; import org.apache.qpid.server.logging.actors.CurrentActor; -import org.apache.qpid.server.plugins.Plugin; import org.apache.qpid.server.queue.AMQQueue; import org.apache.qpid.server.virtualhost.VirtualHost; import org.apache.qpid.server.virtualhost.plugins.logging.SlowConsumerDetectionMessages; import org.apache.qpid.slowconsumerdetection.policies.SlowConsumerPolicyPlugin; +import java.util.Set; +import java.util.concurrent.TimeUnit; + public class SlowConsumerDetection extends VirtualHostHouseKeepingPlugin { private SlowConsumerDetectionConfiguration _config; @@ -61,7 +60,7 @@ public class SlowConsumerDetection extends VirtualHostHouseKeepingPlugin * virtual host to record all the configured queues in a cache for processing by the housekeeping * thread. * - * @see Plugin#configure(ConfigurationPlugin) + * @see org.apache.qpid.server.plugins.Plugin#configure(ConfigurationPlugin) */ public void configure(ConfigurationPlugin config) { @@ -98,7 +97,7 @@ public class SlowConsumerDetection extends VirtualHostHouseKeepingPlugin if (policy == null) { // We would only expect to see this during shutdown - _logger.warn("No slow consumer policy for queue " + q.getName()); + getLogger().warn("No slow consumer policy for queue " + q.getName()); } else { @@ -110,7 +109,7 @@ public class SlowConsumerDetection extends VirtualHostHouseKeepingPlugin catch (Exception e) { // Don't throw exceptions as this will stop the house keeping task from running. - _logger.error("Exception in SlowConsumersDetection for queue: " + q.getName(), e); + getLogger().error("Exception in SlowConsumersDetection for queue: " + q.getName(), e); } } @@ -139,9 +138,9 @@ public class SlowConsumerDetection extends VirtualHostHouseKeepingPlugin { if (config != null) { - if (_logger.isInfoEnabled()) + if (getLogger().isInfoEnabled()) { - _logger.info("Retrieved Queue(" + q.getName() + ") Config:" + config); + getLogger().info("Retrieved Queue(" + q.getName() + ") Config:" + config); } int count = q.getMessageCount(); @@ -157,12 +156,12 @@ public class SlowConsumerDetection extends VirtualHostHouseKeepingPlugin ((count > 0) && q.getOldestMessageArrivalTime() >= config.getMessageAge()))) { - if (_logger.isDebugEnabled()) + if (getLogger().isDebugEnabled()) { - _logger.debug("Detected Slow Consumer on Queue(" + q.getName() + ")"); - _logger.debug("Queue Count:" + q.getMessageCount() + ":" + config.getMessageCount()); - _logger.debug("Queue Depth:" + q.getQueueDepth() + ":" + config.getDepth()); - _logger.debug("Queue Arrival:" + q.getOldestMessageArrivalTime() + ":" + config.getMessageAge()); + getLogger().debug("Detected Slow Consumer on Queue(" + q.getName() + ")"); + getLogger().debug("Queue Count:" + q.getMessageCount() + ":" + config.getMessageCount()); + getLogger().debug("Queue Depth:" + q.getQueueDepth() + ":" + config.getDepth()); + getLogger().debug("Queue Arrival:" + q.getOldestMessageArrivalTime() + ":" + config.getMessageAge()); } return true; diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/VirtualHostHouseKeepingPlugin.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/VirtualHostHouseKeepingPlugin.java index 3798f47f0b..191f8041d2 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/VirtualHostHouseKeepingPlugin.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/VirtualHostHouseKeepingPlugin.java @@ -21,6 +21,7 @@ package org.apache.qpid.server.virtualhost.plugins; import org.apache.log4j.Logger; + import org.apache.qpid.server.virtualhost.HouseKeepingTask; import org.apache.qpid.server.virtualhost.VirtualHost; @@ -28,7 +29,7 @@ import java.util.concurrent.TimeUnit; public abstract class VirtualHostHouseKeepingPlugin extends HouseKeepingTask implements VirtualHostPlugin { - protected final Logger _logger = Logger.getLogger(getClass()); + private final Logger _logger = Logger.getLogger(getClass()); public VirtualHostHouseKeepingPlugin(VirtualHost vhost) { @@ -51,4 +52,10 @@ public abstract class VirtualHostHouseKeepingPlugin extends HouseKeepingTask imp * @see java.util.concurrent.TimeUnit for valid value. */ public abstract TimeUnit getTimeUnit(); + + + protected Logger getLogger() + { + return _logger; + } } diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/VirtualHostPlugin.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/VirtualHostPlugin.java index 1886c2d01d..35f6228ab9 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/VirtualHostPlugin.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/VirtualHostPlugin.java @@ -20,10 +20,9 @@ */ package org.apache.qpid.server.virtualhost.plugins; -import java.util.concurrent.TimeUnit; - import org.apache.qpid.server.plugins.Plugin; -import org.apache.qpid.server.virtualhost.VirtualHost; + +import java.util.concurrent.TimeUnit; public interface VirtualHostPlugin extends Runnable, Plugin { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/policies/TopicDeletePolicy.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/policies/TopicDeletePolicy.java index 6028f63fdb..f2f61f204e 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/policies/TopicDeletePolicy.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/policies/TopicDeletePolicy.java @@ -22,10 +22,10 @@ package org.apache.qpid.server.virtualhost.plugins.policies; import org.apache.commons.configuration.ConfigurationException; import org.apache.log4j.Logger; + import org.apache.qpid.AMQException; import org.apache.qpid.protocol.AMQConstant; import org.apache.qpid.server.binding.Binding; -import org.apache.qpid.server.configuration.plugins.SlowConsumerDetectionPolicyConfiguration; import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin; import org.apache.qpid.server.exchange.TopicExchange; import org.apache.qpid.server.logging.actors.CurrentActor; @@ -37,7 +37,7 @@ import org.apache.qpid.slowconsumerdetection.policies.SlowConsumerPolicyPluginFa public class TopicDeletePolicy implements SlowConsumerPolicyPlugin { - Logger _logger = Logger.getLogger(TopicDeletePolicy.class); + private Logger _logger = Logger.getLogger(TopicDeletePolicy.class); private TopicDeletePolicyConfiguration _configuration; public static class TopicDeletePolicyFactory implements SlowConsumerPolicyPluginFactory diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/policies/TopicDeletePolicyConfiguration.java b/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/policies/TopicDeletePolicyConfiguration.java index 7dfd22c733..48158b7dff 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/policies/TopicDeletePolicyConfiguration.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/policies/TopicDeletePolicyConfiguration.java @@ -20,14 +20,15 @@ */ package org.apache.qpid.server.virtualhost.plugins.policies; -import java.util.Arrays; -import java.util.List; - import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.ConfigurationException; + import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin; import org.apache.qpid.server.configuration.plugins.ConfigurationPluginFactory; +import java.util.Arrays; +import java.util.List; + public class TopicDeletePolicyConfiguration extends ConfigurationPlugin { diff --git a/qpid/java/broker/src/main/java/org/apache/qpid/tools/security/Passwd.java b/qpid/java/broker/src/main/java/org/apache/qpid/tools/security/Passwd.java index 3d3c7b6cc6..cd833c89c4 100644 --- a/qpid/java/broker/src/main/java/org/apache/qpid/tools/security/Passwd.java +++ b/qpid/java/broker/src/main/java/org/apache/qpid/tools/security/Passwd.java @@ -14,9 +14,9 @@ * "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. + * under the License. + * * - * */ package org.apache.qpid.tools.security; @@ -26,8 +26,12 @@ import java.nio.charset.Charset; import java.security.DigestException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; + import org.apache.commons.codec.binary.Base64; +/** + * Utility to generate user:encodedPassword string for use in md5passwd + */ public class Passwd { public static void main(String args[]) throws NoSuchAlgorithmException, DigestException, IOException @@ -63,5 +67,4 @@ public class Passwd String encodedStr = new String(encoded, Charset.forName("utf-8")); return userName + ":" + encodedStr; } - } diff --git a/qpid/java/broker/src/test/java/org/apache/log4j/xml/QpidLog4JConfiguratorTest.java b/qpid/java/broker/src/test/java/org/apache/log4j/xml/QpidLog4JConfiguratorTest.java index 445c7d57f2..c06ce5e31a 100644 --- a/qpid/java/broker/src/test/java/org/apache/log4j/xml/QpidLog4JConfiguratorTest.java +++ b/qpid/java/broker/src/test/java/org/apache/log4j/xml/QpidLog4JConfiguratorTest.java @@ -21,15 +21,14 @@ package org.apache.log4j.xml; +import junit.framework.TestCase; +import org.apache.log4j.xml.QpidLog4JConfigurator.IllegalLoggerLevelException; + import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; -import org.apache.log4j.xml.QpidLog4JConfigurator.IllegalLoggerLevelException; - -import junit.framework.TestCase; - public class QpidLog4JConfiguratorTest extends TestCase { private static final String NEWLINE = System.getProperty("line.separator"); diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/AMQBrokerManagerMBeanTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/AMQBrokerManagerMBeanTest.java index 7d128f2bc5..d34d1bbef3 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/AMQBrokerManagerMBeanTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/AMQBrokerManagerMBeanTest.java @@ -20,10 +20,8 @@ */ package org.apache.qpid.server; -import java.util.HashMap; -import java.util.Map; - import org.apache.commons.configuration.XMLConfiguration; + import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.management.common.mbeans.ManagedBroker; import org.apache.qpid.server.configuration.ServerConfiguration; @@ -40,10 +38,13 @@ import org.apache.qpid.server.registry.ApplicationRegistry; import org.apache.qpid.server.registry.IApplicationRegistry; import org.apache.qpid.server.store.TestableMemoryMessageStore; import org.apache.qpid.server.util.TestApplicationRegistry; -import org.apache.qpid.server.virtualhost.VirtualHostImpl; import org.apache.qpid.server.virtualhost.VirtualHost; +import org.apache.qpid.server.virtualhost.VirtualHostImpl; import org.apache.qpid.test.utils.QpidTestCase; +import java.util.HashMap; +import java.util.Map; + public class AMQBrokerManagerMBeanTest extends QpidTestCase { private QueueRegistry _queueRegistry; diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/BrokerOptionsTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/BrokerOptionsTest.java index 131f316330..bb20e0200b 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/BrokerOptionsTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/BrokerOptionsTest.java @@ -20,13 +20,13 @@ */ package org.apache.qpid.server; +import org.apache.qpid.test.utils.QpidTestCase; + import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Set; -import org.apache.qpid.test.utils.QpidTestCase; - public class BrokerOptionsTest extends QpidTestCase { diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/ExtractResendAndRequeueTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/ExtractResendAndRequeueTest.java index d2408ba21f..616ee74b2d 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/ExtractResendAndRequeueTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/ExtractResendAndRequeueTest.java @@ -21,23 +21,24 @@ package org.apache.qpid.server; import junit.framework.TestCase; + +import org.apache.qpid.AMQException; import org.apache.qpid.server.ack.UnacknowledgedMessageMapImpl; -import org.apache.qpid.server.queue.QueueEntry; -import org.apache.qpid.server.queue.SimpleQueueEntryList; -import org.apache.qpid.server.queue.MockAMQMessage; +import org.apache.qpid.server.message.AMQMessage; import org.apache.qpid.server.queue.AMQQueue; +import org.apache.qpid.server.queue.MockAMQMessage; import org.apache.qpid.server.queue.MockAMQQueue; -import org.apache.qpid.server.message.AMQMessage; +import org.apache.qpid.server.queue.QueueEntry; import org.apache.qpid.server.queue.QueueEntryIterator; -import org.apache.qpid.server.subscription.Subscription; -import org.apache.qpid.server.subscription.MockSubscription; +import org.apache.qpid.server.queue.SimpleQueueEntryList; import org.apache.qpid.server.store.MemoryMessageStore; import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.AMQException; +import org.apache.qpid.server.subscription.MockSubscription; +import org.apache.qpid.server.subscription.Subscription; -import java.util.Map; import java.util.LinkedHashMap; import java.util.LinkedList; +import java.util.Map; /** * QPID-1385 : Race condition between added to unacked map and resending due to a rollback. @@ -59,7 +60,7 @@ import java.util.LinkedList; public class ExtractResendAndRequeueTest extends TestCase { - UnacknowledgedMessageMapImpl _unacknowledgedMessageMap; + private UnacknowledgedMessageMapImpl _unacknowledgedMessageMap; private static final int INITIAL_MSG_COUNT = 10; private AMQQueue _queue = new MockAMQQueue(getName()); private MessageStore _messageStore = new MemoryMessageStore(); diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/MainTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/MainTest.java index 3e4c30291c..31d5028536 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/MainTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/MainTest.java @@ -20,10 +20,11 @@ */ package org.apache.qpid.server; -import java.util.EnumSet; - +import org.apache.commons.cli.CommandLine; import org.apache.qpid.test.utils.QpidTestCase; +import java.util.EnumSet; + /** * Test to verify the command line parsing within the Main class, by * providing it a series of command line arguments and verifying the @@ -145,6 +146,22 @@ public class MainTest extends QpidTestCase assertEquals(9, options.getLogWatchFrequency()); } + public void testVersion() + { + final TestMain main = new TestMain("-v".split("\\s")); + + assertNotNull("Command line not parsed correctly", main.getCommandLine()); + assertTrue("Parsed command line didnt pick up version option", main.getCommandLine().hasOption("v")); + } + + public void testHelp() + { + final TestMain main = new TestMain("-h".split("\\s")); + + assertNotNull("Command line not parsed correctly", main.getCommandLine()); + assertTrue("Parsed command line didnt pick up help option", main.getCommandLine().hasOption("h")); + } + private BrokerOptions startDummyMain(String commandLine) { return (new TestMain(commandLine.split("\\s"))).getOptions(); @@ -174,5 +191,10 @@ public class MainTest extends QpidTestCase { return _options; } + + public CommandLine getCommandLine() + { + return _commandLine; + } } } diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/SelectorParserTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/SelectorParserTest.java index a0304a7b01..3e0e217eee 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/SelectorParserTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/SelectorParserTest.java @@ -1,8 +1,4 @@ -package org.apache.qpid.server; - -import junit.framework.TestCase; -import org.apache.qpid.server.filter.JMSSelectorFilter; -import org.apache.qpid.AMQException;/* +/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -23,6 +19,14 @@ import org.apache.qpid.AMQException;/* * */ +package org.apache.qpid.server; + +import junit.framework.TestCase; + +import org.apache.qpid.filter.SelectorParsingException; +import org.apache.qpid.filter.selector.ParseException; +import org.apache.qpid.server.filter.JMSSelectorFilter; + public class SelectorParserTest extends TestCase { public void testSelectorWithHyphen() @@ -106,7 +110,11 @@ public class SelectorParserTest extends TestCase { new JMSSelectorFilter(selector); } - catch (AMQException e) + catch (ParseException e) + { + fail("Selector '" + selector + "' was not parsed :" + e.getMessage()); + } + catch (SelectorParsingException e) { fail("Selector '" + selector + "' was not parsed :" + e.getMessage()); } @@ -119,7 +127,11 @@ public class SelectorParserTest extends TestCase new JMSSelectorFilter(selector); fail("Selector '" + selector + "' was parsed "); } - catch (AMQException e) + catch (ParseException e) + { + //normal path + } + catch (SelectorParsingException e) { //normal path } diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/QueueConfigurationTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/QueueConfigurationTest.java index e1a5e7d338..36f131a30f 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/QueueConfigurationTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/QueueConfigurationTest.java @@ -24,6 +24,7 @@ import junit.framework.TestCase; import org.apache.commons.configuration.CompositeConfiguration; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.PropertiesConfiguration; + import org.apache.qpid.server.registry.ApplicationRegistry; import org.apache.qpid.server.util.TestApplicationRegistry; diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/ServerConfigurationTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/ServerConfigurationTest.java index eb4a90d9f3..4caefc2f18 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/ServerConfigurationTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/ServerConfigurationTest.java @@ -20,16 +20,9 @@ */ package org.apache.qpid.server.configuration; -import static org.apache.qpid.transport.ConnectionSettings.WILDCARD_ADDRESS; - -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.Writer; -import java.util.Locale; - import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.XMLConfiguration; + import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.server.exchange.Exchange; import org.apache.qpid.server.registry.ApplicationRegistry; @@ -39,6 +32,16 @@ import org.apache.qpid.server.virtualhost.VirtualHost; import org.apache.qpid.server.virtualhost.VirtualHostRegistry; import org.apache.qpid.test.utils.QpidTestCase; +import static org.apache.qpid.transport.ConnectionSettings.WILDCARD_ADDRESS; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.Writer; +import java.util.Locale; + +import javax.net.ssl.KeyManagerFactory; + public class ServerConfigurationTest extends QpidTestCase { private XMLConfiguration _config = new XMLConfiguration(); @@ -490,19 +493,6 @@ public class ServerConfigurationTest extends QpidTestCase assertEquals(false, _serverConfig.getTcpNoDelay()); } - public void testGetEnableExecutorPool() throws ConfigurationException - { - // Check default - _serverConfig.initialise(); - assertEquals(false, _serverConfig.getEnableExecutorPool()); - - // Check value we set - _config.setProperty("advanced.filterchain[@enableExecutorPool]", true); - _serverConfig = new ServerConfiguration(_config); - _serverConfig.initialise(); - assertEquals(true, _serverConfig.getEnableExecutorPool()); - } - public void testGetEnableSSL() throws ConfigurationException { // Check default @@ -587,17 +577,24 @@ public class ServerConfigurationTest extends QpidTestCase assertEquals("b", _serverConfig.getConnectorKeyStorePassword()); } - public void testGetConnectorCertType() throws ConfigurationException + public void testConnectorGetKeyManagerAlgorithm() throws ConfigurationException { // Check default _serverConfig.initialise(); - assertEquals("SunX509", _serverConfig.getConnectorCertType()); + assertEquals(KeyManagerFactory.getDefaultAlgorithm(), _serverConfig.getConnectorKeyManagerFactoryAlgorithm()); // Check value we set - _config.setProperty("connector.ssl.certType", "a"); + _config.setProperty("connector.ssl.keyManagerFactoryAlgorithm", "a"); + _serverConfig = new ServerConfiguration(_config); + _serverConfig.initialise(); + assertEquals("a", _serverConfig.getConnectorKeyManagerFactoryAlgorithm()); + + // Ensure we continue to support the old name certType + _config.clearProperty("connector.ssl.keyManagerFactoryAlgorithm"); + _config.setProperty("connector.ssl.certType", "b"); _serverConfig = new ServerConfiguration(_config); _serverConfig.initialise(); - assertEquals("a", _serverConfig.getConnectorCertType()); + assertEquals("b", _serverConfig.getConnectorKeyManagerFactoryAlgorithm()); } public void testGetHousekeepingCheckPeriod() throws ConfigurationException @@ -1539,6 +1536,58 @@ public class ServerConfigurationTest extends QpidTestCase assertTrue("C3P0 queue DLQ should be enabled, using broker default", c3p0.isDeadLetterQueueEnabled()); } + public void testIsAmqp010enabled() throws ConfigurationException + { + // Check default + _serverConfig.initialise(); + assertEquals(true, _serverConfig.isAmqp010enabled()); + + // Check value we set + _config.setProperty(ServerConfiguration.CONNECTOR_AMQP010ENABLED, false); + _serverConfig = new ServerConfiguration(_config); + _serverConfig.initialise(); + assertEquals(false, _serverConfig.isAmqp010enabled()); + } + + public void testIsAmqp091enabled() throws ConfigurationException + { + // Check default + _serverConfig.initialise(); + assertEquals(true, _serverConfig.isAmqp091enabled()); + + // Check value we set + _config.setProperty(ServerConfiguration.CONNECTOR_AMQP091ENABLED, false); + _serverConfig = new ServerConfiguration(_config); + _serverConfig.initialise(); + assertEquals(false, _serverConfig.isAmqp091enabled()); + } + + public void testIsAmqp09enabled() throws ConfigurationException + { + // Check default + _serverConfig.initialise(); + assertEquals(true, _serverConfig.isAmqp09enabled()); + + // Check value we set + _config.setProperty(ServerConfiguration.CONNECTOR_AMQP09ENABLED, false); + _serverConfig = new ServerConfiguration(_config); + _serverConfig.initialise(); + assertEquals(false, _serverConfig.isAmqp09enabled()); + } + + public void testIsAmqp08enabled() throws ConfigurationException + { + // Check default + _serverConfig.initialise(); + assertEquals(true, _serverConfig.isAmqp08enabled()); + + // Check value we set + _config.setProperty(ServerConfiguration.CONNECTOR_AMQP08ENABLED, false); + _serverConfig = new ServerConfiguration(_config); + _serverConfig.initialise(); + assertEquals(false, _serverConfig.isAmqp08enabled()); + } + /** * Convenience method to output required security preamble for broker config */ diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/TopicConfigurationTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/TopicConfigurationTest.java index 7fc3b2d06a..59cd0cf1db 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/TopicConfigurationTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/TopicConfigurationTest.java @@ -21,6 +21,7 @@ package org.apache.qpid.server.configuration; import org.apache.commons.configuration.ConfigurationException; + import org.apache.qpid.AMQException; import org.apache.qpid.AMQInternalException; import org.apache.qpid.AMQSecurityException; diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/VirtualHostConfigurationTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/VirtualHostConfigurationTest.java index f6cd397217..50e7f0588b 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/VirtualHostConfigurationTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/VirtualHostConfigurationTest.java @@ -21,6 +21,7 @@ package org.apache.qpid.server.configuration; import org.apache.commons.configuration.ConfigurationException; + import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.server.queue.AMQPriorityQueue; import org.apache.qpid.server.queue.AMQQueue; diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/plugins/ConfigurationPluginTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/plugins/ConfigurationPluginTest.java index ee2f77f16b..14c7b8cb20 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/plugins/ConfigurationPluginTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/configuration/plugins/ConfigurationPluginTest.java @@ -20,10 +20,10 @@ */ package org.apache.qpid.server.configuration.plugins; -import junit.framework.TestCase; import org.apache.commons.configuration.CompositeConfiguration; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.XMLConfiguration; + import org.apache.qpid.server.util.InternalBrokerBaseCase; import java.util.List; @@ -68,7 +68,7 @@ public class ConfigurationPluginTest extends InternalBrokerBaseCase } - ConfigPlugin _plugin; + private ConfigPlugin _plugin; @Override public void setUp() throws Exception diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/exchange/AbstractHeadersExchangeTestBase.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/exchange/AbstractHeadersExchangeTestBase.java index 7bd711a19c..9011e50741 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/exchange/AbstractHeadersExchangeTestBase.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/exchange/AbstractHeadersExchangeTestBase.java @@ -20,17 +20,8 @@ */ package org.apache.qpid.server.exchange; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.atomic.AtomicLong; import org.apache.log4j.Logger; + import org.apache.qpid.AMQException; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.framing.BasicContentHeaderProperties; @@ -55,11 +46,21 @@ import org.apache.qpid.server.queue.SimpleAMQQueue; import org.apache.qpid.server.registry.ApplicationRegistry; import org.apache.qpid.server.store.DurableConfigurationStore; import org.apache.qpid.server.store.MemoryMessageStore; -import org.apache.qpid.server.store.MessageStore; import org.apache.qpid.server.store.StoredMessage; import org.apache.qpid.server.subscription.Subscription; import org.apache.qpid.server.util.InternalBrokerBaseCase; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.atomic.AtomicLong; + public class AbstractHeadersExchangeTestBase extends InternalBrokerBaseCase { private static final Logger _log = Logger.getLogger(AbstractHeadersExchangeTestBase.class); @@ -75,7 +76,7 @@ public class AbstractHeadersExchangeTestBase extends InternalBrokerBaseCase private MemoryMessageStore _store = new MemoryMessageStore(); - BindingFactory bindingFactory = new BindingFactory(new DurableConfigurationStore.Source() + private BindingFactory bindingFactory = new BindingFactory(new DurableConfigurationStore.Source() { public DurableConfigurationStore getDurableConfigurationStore() @@ -122,7 +123,7 @@ public class AbstractHeadersExchangeTestBase extends InternalBrokerBaseCase protected int route(Message m) throws AMQException { - m.getIncomingMessage().headersReceived(); + m.getIncomingMessage().headersReceived(System.currentTimeMillis()); m.route(exchange); if(m.getIncomingMessage().allContentReceived()) { @@ -287,7 +288,7 @@ public class AbstractHeadersExchangeTestBase extends InternalBrokerBaseCase static class TestQueue extends SimpleAMQQueue { - final List messages = new ArrayList(); + private final List messages = new ArrayList(); public String toString() { @@ -496,18 +497,15 @@ public class AbstractHeadersExchangeTestBase extends InternalBrokerBaseCase return null; } - @Override public int getDeliveryCount() { return 0; } - @Override public void incrementDeliveryCount() { } - @Override public void decrementDeliveryCount() { } @@ -594,8 +592,8 @@ public class AbstractHeadersExchangeTestBase extends InternalBrokerBaseCase int pos = 0; for(ContentBody body : bodies) { - storedMessage.addContent(pos, ByteBuffer.wrap(body._payload)); - pos += body._payload.length; + storedMessage.addContent(pos, ByteBuffer.wrap(body.getPayload())); + pos += body.getPayload().length; } _incoming = new TestIncomingMessage(getMessageId(),publish, protocolsession); diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/exchange/ExchangeMBeanTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/exchange/ExchangeMBeanTest.java index 68021f0b07..1fac4afe29 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/exchange/ExchangeMBeanTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/exchange/ExchangeMBeanTest.java @@ -21,17 +21,18 @@ package org.apache.qpid.server.exchange; import org.apache.commons.lang.ArrayUtils; + +import org.apache.qpid.exchange.ExchangeDefaults; +import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.management.common.mbeans.ManagedExchange; -import org.apache.qpid.server.queue.QueueRegistry; +import org.apache.qpid.server.management.ManagedObject; import org.apache.qpid.server.queue.AMQQueue; import org.apache.qpid.server.queue.AMQQueueFactory; +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.util.InternalBrokerBaseCase; import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.exchange.ExchangeDefaults; -import org.apache.qpid.framing.AMQShortString; import javax.management.JMException; import javax.management.openmbean.CompositeDataSupport; diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/exchange/HeadersBindingTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/exchange/HeadersBindingTest.java index a7c226cbd8..4305cdadc6 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/exchange/HeadersBindingTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/exchange/HeadersBindingTest.java @@ -20,16 +20,16 @@ */ package org.apache.qpid.server.exchange; -import java.util.Map; -import java.util.HashMap; -import java.util.Set; - import junit.framework.TestCase; -import org.apache.qpid.framing.FieldTable; + import org.apache.qpid.server.binding.Binding; import org.apache.qpid.server.message.AMQMessageHeader; import org.apache.qpid.server.queue.MockAMQQueue; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + /** */ public class HeadersBindingTest extends TestCase diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/exchange/HeadersExchangeTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/exchange/HeadersExchangeTest.java index ac638e4e6a..326d36df05 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/exchange/HeadersExchangeTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/exchange/HeadersExchangeTest.java @@ -21,14 +21,14 @@ package org.apache.qpid.server.exchange; import org.apache.qpid.AMQException; +import org.apache.qpid.server.protocol.AMQProtocolSession; +import org.apache.qpid.server.protocol.InternalTestProtocolSession; import org.apache.qpid.server.registry.ApplicationRegistry; import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.server.protocol.InternalTestProtocolSession; -import org.apache.qpid.server.protocol.AMQProtocolSession; public class HeadersExchangeTest extends AbstractHeadersExchangeTestBase { - AMQProtocolSession _protocolSession; + private AMQProtocolSession _protocolSession; @Override public void setUp() throws Exception diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/exchange/TopicExchangeTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/exchange/TopicExchangeTest.java index 403a290a0f..00c8a18d9f 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/exchange/TopicExchangeTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/exchange/TopicExchangeTest.java @@ -20,33 +20,36 @@ */ package org.apache.qpid.server.exchange; -import junit.framework.TestCase; import junit.framework.Assert; -import org.apache.qpid.server.queue.*; -import org.apache.qpid.server.util.InternalBrokerBaseCase; -import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.store.MessageStore; -import org.apache.qpid.server.store.MemoryMessageStore; -import org.apache.qpid.server.protocol.InternalTestProtocolSession; -import org.apache.qpid.server.binding.Binding; -import org.apache.qpid.server.message.AMQMessage; -import org.apache.qpid.server.message.MessageMetaData; + import org.apache.qpid.AMQException; import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.ContentHeaderBody; import org.apache.qpid.framing.BasicContentHeaderProperties; +import org.apache.qpid.framing.ContentHeaderBody; import org.apache.qpid.framing.abstraction.MessagePublishInfo; +import org.apache.qpid.server.binding.Binding; +import org.apache.qpid.server.message.AMQMessage; +import org.apache.qpid.server.message.MessageMetaData; +import org.apache.qpid.server.protocol.InternalTestProtocolSession; +import org.apache.qpid.server.queue.AMQQueue; +import org.apache.qpid.server.queue.AMQQueueFactory; +import org.apache.qpid.server.queue.BaseQueue; +import org.apache.qpid.server.queue.IncomingMessage; +import org.apache.qpid.server.registry.ApplicationRegistry; +import org.apache.qpid.server.store.MemoryMessageStore; +import org.apache.qpid.server.store.MessageStore; +import org.apache.qpid.server.util.InternalBrokerBaseCase; +import org.apache.qpid.server.virtualhost.VirtualHost; public class TopicExchangeTest extends InternalBrokerBaseCase { - TopicExchange _exchange; + private TopicExchange _exchange; - VirtualHost _vhost; - MessageStore _store; + private VirtualHost _vhost; + private MessageStore _store; - InternalTestProtocolSession _protocolSession; + private InternalTestProtocolSession _protocolSession; @Override @@ -347,7 +350,7 @@ public class TopicExchangeTest extends InternalBrokerBaseCase private int routeMessage(final IncomingMessage message) throws AMQException { - MessageMetaData mmd = message.headersReceived(); + MessageMetaData mmd = message.headersReceived(System.currentTimeMillis()); message.setStoredMessage(_store.addMessage(mmd)); message.enqueue(_exchange.route(message)); @@ -406,7 +409,7 @@ public class TopicExchangeTest extends InternalBrokerBaseCase class PublishInfo implements MessagePublishInfo { - AMQShortString _routingkey; + private AMQShortString _routingkey; PublishInfo(AMQShortString routingkey) { diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/flow/WindowCreditManagerTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/flow/WindowCreditManagerTest.java index 2011dfbda6..bc651c9748 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/flow/WindowCreditManagerTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/flow/WindowCreditManagerTest.java @@ -24,7 +24,7 @@ import org.apache.qpid.test.utils.QpidTestCase; public class WindowCreditManagerTest extends QpidTestCase { - WindowCreditManager _creditManager; + private WindowCreditManager _creditManager; protected void setUp() throws Exception { diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/Log4jMessageLoggerTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/Log4jMessageLoggerTest.java index a845bff9ce..e2a6a56ee2 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/Log4jMessageLoggerTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/Log4jMessageLoggerTest.java @@ -20,23 +20,23 @@ */ package org.apache.qpid.server.logging; -import java.io.IOException; -import java.util.LinkedList; -import java.util.List; - import junit.framework.TestCase; - import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.spi.LoggingEvent; + import org.apache.qpid.server.logging.actors.BrokerActor; +import java.io.IOException; +import java.util.LinkedList; +import java.util.List; + /** Test that the Log4jMessageLogger defaults behave as expected */ public class Log4jMessageLoggerTest extends TestCase { - Level _rootLevel; - Log4jTestAppender _appender; + private Level _rootLevel; + private Log4jTestAppender _appender; @Override public void setUp() throws IOException @@ -242,7 +242,7 @@ public class Log4jMessageLoggerTest extends TestCase */ private class Log4jTestAppender extends AppenderSkeleton { - List _log = new LinkedList(); + private List _log = new LinkedList(); protected void append(LoggingEvent loggingEvent) { diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/LogMessageTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/LogMessageTest.java index 956bb6f8fa..b0cb0ca0ab 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/LogMessageTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/LogMessageTest.java @@ -21,6 +21,7 @@ package org.apache.qpid.server.logging; import junit.framework.TestCase; + import org.apache.qpid.server.logging.messages.BrokerMessages; import java.util.Locale; diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/UnitTestMessageLogger.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/UnitTestMessageLogger.java index e8defd0e58..fabbe8640e 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/UnitTestMessageLogger.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/UnitTestMessageLogger.java @@ -20,12 +20,11 @@ */ package org.apache.qpid.server.logging; +import org.apache.qpid.server.configuration.ServerConfiguration; + import java.util.LinkedList; import java.util.List; -import org.apache.qpid.server.configuration.ServerConfiguration; -import org.apache.qpid.server.logging.AbstractRootMessageLogger; - public class UnitTestMessageLogger extends AbstractRootMessageLogger { private final List _log = new LinkedList(); diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/AMQPChannelActorTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/AMQPChannelActorTest.java index 6346fff85f..f739d3fcb9 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/AMQPChannelActorTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/AMQPChannelActorTest.java @@ -20,11 +20,12 @@ */ package org.apache.qpid.server.logging.actors; -import java.util.List; - import org.apache.commons.configuration.ConfigurationException; + import org.apache.qpid.AMQException; +import java.util.List; + /** * Test : AMQPChannelActorTest * Validate the AMQPChannelActor class. diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/BaseActorTestCase.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/BaseActorTestCase.java index 60ecbef438..ec2cdd5585 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/BaseActorTestCase.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/BaseActorTestCase.java @@ -21,12 +21,11 @@ package org.apache.qpid.server.logging.actors; import org.apache.qpid.server.configuration.ServerConfiguration; +import org.apache.qpid.server.logging.LogActor; import org.apache.qpid.server.logging.LogMessage; import org.apache.qpid.server.logging.LogSubject; import org.apache.qpid.server.logging.RootMessageLogger; -import org.apache.qpid.server.logging.LogActor; import org.apache.qpid.server.logging.UnitTestMessageLogger; - import org.apache.qpid.server.util.InternalBrokerBaseCase; public class BaseActorTestCase extends InternalBrokerBaseCase diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/CurrentActorTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/CurrentActorTest.java index 9a065ea2db..f73765f5aa 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/CurrentActorTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/CurrentActorTest.java @@ -21,6 +21,7 @@ package org.apache.qpid.server.logging.actors; import org.apache.commons.configuration.ConfigurationException; + import org.apache.qpid.AMQException; import org.apache.qpid.server.AMQChannel; import org.apache.qpid.server.logging.LogActor; @@ -202,7 +203,7 @@ public class CurrentActorTest extends BaseConnectionActorTestCase */ public class LogMessagesWithAConnectionActor extends Thread { - Throwable _exception; + private Throwable _exception; public LogMessagesWithAConnectionActor() { @@ -228,13 +229,17 @@ public class CurrentActorTest extends BaseConnectionActorTestCase // Verify it was the same actor as we set earlier if(!actor.equals(CurrentActor.get())) - throw new IllegalArgumentException("Retrieved actor is not as expected "); + { + throw new IllegalArgumentException("Retrieved actor is not as expected "); + } // Verify that removing the actor works for this thread CurrentActor.remove(); if(CurrentActor.get() != defaultActor) - throw new IllegalArgumentException("CurrentActor ("+CurrentActor.get()+") should be default actor" + defaultActor); + { + throw new IllegalArgumentException("CurrentActor ("+CurrentActor.get()+") should be default actor" + defaultActor); + } } catch (Throwable e) { diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/ManagementActorTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/ManagementActorTest.java index d6b790db01..b431047d66 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/ManagementActorTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/ManagementActorTest.java @@ -20,13 +20,12 @@ */ package org.apache.qpid.server.logging.actors; +import javax.management.remote.JMXPrincipal; +import javax.security.auth.Subject; import java.security.PrivilegedAction; import java.util.Collections; import java.util.List; -import javax.management.remote.JMXPrincipal; -import javax.security.auth.Subject; - /** * Test : AMQPManagementActorTest * Validate the AMQPManagementActor class. diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/SubscriptionActorTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/SubscriptionActorTest.java index a2272cc395..8eaa165853 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/SubscriptionActorTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/actors/SubscriptionActorTest.java @@ -20,10 +20,10 @@ */ package org.apache.qpid.server.logging.actors; -import java.util.List; - import org.apache.qpid.server.subscription.MockSubscription; +import java.util.List; + /** * Test : AMQPConnectionActorTest * Validate the AMQPConnectionActor class. diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/management/LoggingManagementMBeanTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/management/LoggingManagementMBeanTest.java index 2d25a769aa..f9ad81ae74 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/management/LoggingManagementMBeanTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/management/LoggingManagementMBeanTest.java @@ -20,9 +20,17 @@ */ package org.apache.qpid.server.logging.management; +import org.apache.log4j.Level; +import org.apache.log4j.Logger; + +import org.apache.qpid.server.util.InternalBrokerBaseCase; + import static org.apache.qpid.management.common.mbeans.LoggingManagement.LOGGER_LEVEL; import static org.apache.qpid.management.common.mbeans.LoggingManagement.LOGGER_NAME; +import javax.management.JMException; +import javax.management.openmbean.CompositeData; +import javax.management.openmbean.TabularDataSupport; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; @@ -31,17 +39,6 @@ import java.util.Collection; import java.util.HashMap; import java.util.Map; -import javax.management.JMException; -import javax.management.openmbean.CompositeData; -import javax.management.openmbean.TabularDataSupport; - -import org.apache.log4j.Level; -import org.apache.log4j.Logger; -import org.apache.qpid.management.common.mbeans.LoggingManagement; - -import junit.framework.TestCase; -import org.apache.qpid.server.util.InternalBrokerBaseCase; - public class LoggingManagementMBeanTest extends InternalBrokerBaseCase { private static final String TEST_LOGGER = "LoggingManagementMBeanTestLogger"; diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/AbstractTestMessages.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/AbstractTestMessages.java index e253881d09..24e7225d82 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/AbstractTestMessages.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/AbstractTestMessages.java @@ -20,10 +20,9 @@ */ package org.apache.qpid.server.logging.messages; -import java.util.List; - import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.PropertiesConfiguration; + import org.apache.qpid.server.logging.LogActor; import org.apache.qpid.server.logging.LogMessage; import org.apache.qpid.server.logging.LogSubject; @@ -32,6 +31,8 @@ import org.apache.qpid.server.logging.actors.TestLogActor; import org.apache.qpid.server.logging.subjects.TestBlankSubject; import org.apache.qpid.server.util.InternalBrokerBaseCase; +import java.util.List; + public abstract class AbstractTestMessages extends InternalBrokerBaseCase { protected Configuration _config = new PropertiesConfiguration(); @@ -62,16 +63,21 @@ public abstract class AbstractTestMessages extends InternalBrokerBaseCase return _logger.getLogMessages(); } + protected void validateLogMessage(List logs, String tag, String[] expected) + { + validateLogMessage(logs, tag, false, expected); + } + /** - * Validate that only a single log messasge occured and that the message + * Validate that only a single log message occurred and that the message * section starts with the specified tag * * @param logs the logs generated during test run * @param tag the tag to check for * @param expected the expected log messages - * + * @param useStringForNull replace a null String reference with "null" */ - protected void validateLogMessage(List logs, String tag, String[] expected) + protected void validateLogMessage(List logs, String tag, boolean useStringForNull, String[] expected) { assertEquals("Log has incorrect message count", 1, logs.size()); @@ -96,6 +102,10 @@ public abstract class AbstractTestMessages extends InternalBrokerBaseCase int index = 0; for (String text : expected) { + if(useStringForNull && text == null) + { + text = "null"; + } index = message.indexOf(text, index); assertTrue("Message does not contain expected (" + text + ") text :" + message, index != -1); index = index + text.length(); diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/BrokerMessagesTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/BrokerMessagesTest.java index a3d46f5716..e87d292471 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/BrokerMessagesTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/BrokerMessagesTest.java @@ -22,6 +22,8 @@ package org.apache.qpid.server.logging.messages; import java.util.List; +import org.apache.derby.iapi.services.io.FileUtil; + /** * Test BRK log Messages */ @@ -64,7 +66,7 @@ public class BrokerMessagesTest extends AbstractTestMessages List log = performLog(); - String[] expected = {"Shuting down", transport, "port ", String.valueOf(port)}; + String[] expected = {"Shutting down", transport, "port ", String.valueOf(port)}; validateLogMessage(log, "BRK-1003", expected); } @@ -113,4 +115,33 @@ public class BrokerMessagesTest extends AbstractTestMessages validateLogMessage(log, "BRK-1007", expected); } + public void testBrokerPlatform() + { + String javaVendor = "jvendor"; + String javaVersion = "j1.0"; + + String osName = "os"; + String osVersion = "o1.0"; + String osArch = "oarch"; + + _logMessage = BrokerMessages.PLATFORM(javaVendor, javaVersion, osName, osVersion, osArch); + List log = performLog(); + + String[] expected = {"Platform :", "JVM :", javaVendor, " version: ", " OS : ", osName, " version: ", osVersion, " arch: ", osArch}; + + validateLogMessage(log, "BRK-1010", expected); + } + + public void testBrokerMemory() + { + long oneGiga = 1024*1024*1024; + + _logMessage = BrokerMessages.MAX_MEMORY(oneGiga); + List log = performLog(); + + String[] expected = {"Maximum Memory :", "1,073,741,824", "bytes"}; + + validateLogMessage(log, "BRK-1011", expected); + } + } diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/ConnectionMessagesTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/ConnectionMessagesTest.java index 24fccf8446..b2951ae54a 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/ConnectionMessagesTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/messages/ConnectionMessagesTest.java @@ -27,25 +27,27 @@ import java.util.List; */ public class ConnectionMessagesTest extends AbstractTestMessages { - public void testConnectionOpen_WithClientIDProtocolVersion() + public void testConnectionOpen_WithClientIDProtocolVersionClientVersion() { String clientID = "client"; String protocolVersion = "8-0"; + String clientVersion = "1.2.3_4"; - _logMessage = ConnectionMessages.OPEN(clientID, protocolVersion, true , true); + _logMessage = ConnectionMessages.OPEN(clientID, protocolVersion, clientVersion, true , true, true); List log = performLog(); String[] expected = {"Open :", "Client ID", clientID, - ": Protocol Version :", protocolVersion}; + ": Protocol Version :", protocolVersion, + ": Client Version :", clientVersion}; validateLogMessage(log, "CON-1001", expected); } - public void testConnectionOpen_WithClientIDNoProtocolVersion() + public void testConnectionOpen_WithClientIDNoProtocolVersionNoClientVersion() { String clientID = "client"; - _logMessage = ConnectionMessages.OPEN(clientID, null,true, false); + _logMessage = ConnectionMessages.OPEN(clientID, null, null, true, false, false); List log = performLog(); String[] expected = {"Open :", "Client ID", clientID}; @@ -53,11 +55,11 @@ public class ConnectionMessagesTest extends AbstractTestMessages validateLogMessage(log, "CON-1001", expected); } - public void testConnectionOpen_WithNOClientIDProtocolVersion() + public void testConnectionOpen_WithNOClientIDProtocolVersionNoClientVersion() { String protocolVersion = "8-0"; - _logMessage = ConnectionMessages.OPEN(null, protocolVersion, false , true); + _logMessage = ConnectionMessages.OPEN(null, protocolVersion, null, false , true, false); List log = performLog(); String[] expected = {"Open", ": Protocol Version :", protocolVersion}; @@ -65,17 +67,39 @@ public class ConnectionMessagesTest extends AbstractTestMessages validateLogMessage(log, "CON-1001", expected); } - public void testConnectionOpen_WithNoClientIDNoProtocolVersion() + public void testConnectionOpen_WithNOClientIDNoProtocolVersionClientVersion() { - _logMessage = ConnectionMessages.OPEN(null, null,false, false); + String clientVersion = "1.2.3_4"; + + _logMessage = ConnectionMessages.OPEN(null, null, clientVersion, false , false, true); List log = performLog(); - String[] expected = {"Open"}; + String[] expected = {"Open", ": Client Version :", clientVersion}; validateLogMessage(log, "CON-1001", expected); } + public void testConnectionOpen_WithNOClientIDNoProtocolVersionNullClientVersion() + { + String clientVersion = null; + + _logMessage = ConnectionMessages.OPEN(null, null, clientVersion , false , false, true); + List log = performLog(); + + String[] expected = {"Open", ": Client Version :", clientVersion}; + + validateLogMessage(log, "CON-1001", true, expected); + } + public void testConnectionOpen_WithNoClientIDNoProtocolVersionNoClientVersion() + { + _logMessage = ConnectionMessages.OPEN(null, null, null, false, false, false); + List log = performLog(); + + String[] expected = {"Open"}; + + validateLogMessage(log, "CON-1001", expected); + } public void testConnectionClose() { diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/AbstractTestLogSubject.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/AbstractTestLogSubject.java index 1cd8d55b0d..c2558d2d1b 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/AbstractTestLogSubject.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/AbstractTestLogSubject.java @@ -20,26 +20,21 @@ */ package org.apache.qpid.server.logging.subjects; -import junit.framework.TestCase; import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.PropertiesConfiguration; + import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.server.configuration.ServerConfiguration; import org.apache.qpid.server.exchange.Exchange; import org.apache.qpid.server.logging.LogActor; import org.apache.qpid.server.logging.LogMessage; import org.apache.qpid.server.logging.LogSubject; -import org.apache.qpid.server.logging.RootMessageLogger; -import org.apache.qpid.server.logging.AbstractRootMessageLogger; import org.apache.qpid.server.logging.UnitTestMessageLogger; import org.apache.qpid.server.logging.actors.TestLogActor; import org.apache.qpid.server.queue.AMQQueue; import org.apache.qpid.server.util.InternalBrokerBaseCase; import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.protocol.InternalTestProtocolSession; -import org.apache.qpid.server.protocol.AMQProtocolSession; import java.util.List; diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/ExchangeLogSubjectTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/ExchangeLogSubjectTest.java index 7e16516fc6..cc06b05bf6 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/ExchangeLogSubjectTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/ExchangeLogSubjectTest.java @@ -30,8 +30,8 @@ import org.apache.qpid.server.virtualhost.VirtualHost; */ public class ExchangeLogSubjectTest extends AbstractTestLogSubject { - Exchange _exchange; - VirtualHost _testVhost; + private Exchange _exchange; + private VirtualHost _testVhost; public void setUp() throws Exception { diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/MessageStoreLogSubjectTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/MessageStoreLogSubjectTest.java index 9c868ea651..158fb667a9 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/MessageStoreLogSubjectTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/MessageStoreLogSubjectTest.java @@ -20,15 +20,15 @@ */ package org.apache.qpid.server.logging.subjects; -import org.apache.qpid.server.virtualhost.VirtualHost; import org.apache.qpid.server.registry.ApplicationRegistry; +import org.apache.qpid.server.virtualhost.VirtualHost; /** * Validate MessageStoreLogSubjects are logged as expected */ public class MessageStoreLogSubjectTest extends AbstractTestLogSubject { - VirtualHost _testVhost; + private VirtualHost _testVhost; public void setUp() throws Exception { diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/TestBlankSubject.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/TestBlankSubject.java index 89688e13b3..7684db0b3d 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/TestBlankSubject.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/logging/subjects/TestBlankSubject.java @@ -27,7 +27,7 @@ public class TestBlankSubject extends AbstractLogSubject { public TestBlankSubject() { - _logString = "[TestBlankSubject]"; + setLogString("[TestBlankSubject]"); } } diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/management/AMQUserManagementMBeanTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/management/AMQUserManagementMBeanTest.java index f3ee2707b0..f7d85c11a8 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/management/AMQUserManagementMBeanTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/management/AMQUserManagementMBeanTest.java @@ -21,22 +21,18 @@ package org.apache.qpid.server.management; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; - -import javax.management.openmbean.CompositeData; -import javax.management.openmbean.TabularData; - - -import org.apache.commons.lang.NotImplementedException; import org.apache.qpid.management.common.mbeans.UserManagement; import org.apache.qpid.server.security.auth.database.PlainPasswordFilePrincipalDatabase; import org.apache.qpid.server.security.auth.management.AMQUserManagementMBean; - import org.apache.qpid.server.util.InternalBrokerBaseCase; +import javax.management.openmbean.CompositeData; +import javax.management.openmbean.TabularData; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; + /** * * Tests the AMQUserManagementMBean and its interaction with the PrincipalDatabase. diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/plugins/OsgiSystemPackageUtilTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/plugins/OsgiSystemPackageUtilTest.java index f2249c5931..267545c656 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/plugins/OsgiSystemPackageUtilTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/plugins/OsgiSystemPackageUtilTest.java @@ -20,11 +20,12 @@ */ package org.apache.qpid.server.plugins; -import java.util.Map; -import java.util.TreeMap; +import org.osgi.framework.Version; import org.apache.qpid.test.utils.QpidTestCase; -import org.osgi.framework.Version; + +import java.util.Map; +import java.util.TreeMap; /** * @@ -72,11 +73,11 @@ public class OsgiSystemPackageUtilTest extends QpidTestCase _map.put("org.apache.qpid.xyz", "1.0.0"); _map.put("org.abc", "1.2.3"); - _util = new OsgiSystemPackageUtil(new Version("0.15"), _map); + _util = new OsgiSystemPackageUtil(new Version("0.17"), _map); final String systemPackageString = _util.getFormattedSystemPackageString(); - assertEquals("org.abc; version=1.2.3, org.apache.qpid.xyz; version=0.15.0", systemPackageString); + assertEquals("org.abc; version=1.2.3, org.apache.qpid.xyz; version=0.17.0", systemPackageString); } public void testWithQpidPackageWithoutQpidReleaseNumberSet() throws Exception diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/plugins/PluginTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/plugins/PluginTest.java index 8c945aabfb..b4bda9a032 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/plugins/PluginTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/plugins/PluginTest.java @@ -21,7 +21,6 @@ package org.apache.qpid.server.plugins; import org.apache.qpid.server.exchange.ExchangeType; import org.apache.qpid.server.util.InternalBrokerBaseCase; - import java.util.Map; public class PluginTest extends InternalBrokerBaseCase diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/protocol/AMQProtocolSessionMBeanTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/protocol/AMQProtocolSessionMBeanTest.java index e1dae5fcc1..71d5211470 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/protocol/AMQProtocolSessionMBeanTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/protocol/AMQProtocolSessionMBeanTest.java @@ -20,10 +20,8 @@ */ package org.apache.qpid.server.protocol; -import javax.management.JMException; -import javax.management.openmbean.CompositeData; -import javax.management.openmbean.TabularData; import org.apache.log4j.Logger; + import org.apache.qpid.AMQException; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.management.common.mbeans.ManagedConnection; @@ -36,6 +34,10 @@ import org.apache.qpid.server.store.SkeletonMessageStore; import org.apache.qpid.server.util.InternalBrokerBaseCase; import org.apache.qpid.server.virtualhost.VirtualHost; +import javax.management.JMException; +import javax.management.openmbean.CompositeData; +import javax.management.openmbean.TabularData; + /** Test class to test MBean operations for AMQMinaProtocolSession. */ public class AMQProtocolSessionMBeanTest extends InternalBrokerBaseCase diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/protocol/InternalTestProtocolSession.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/protocol/InternalTestProtocolSession.java index 3c76252cb2..96c67941f9 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/protocol/InternalTestProtocolSession.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/protocol/InternalTestProtocolSession.java @@ -20,17 +20,6 @@ */ package org.apache.qpid.server.protocol; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; - -import javax.security.auth.Subject; - import org.apache.qpid.AMQException; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.framing.ContentHeaderBody; @@ -49,10 +38,20 @@ import org.apache.qpid.server.subscription.SubscriptionImpl; import org.apache.qpid.server.virtualhost.VirtualHost; import org.apache.qpid.transport.TestNetworkConnection; +import javax.security.auth.Subject; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; + public class InternalTestProtocolSession extends AMQProtocolEngine implements ProtocolOutputConverter { // ChannelID(LIST) -> LinkedList - final Map>> _channelDelivers; + private final Map>> _channelDelivers; private AtomicInteger _deliveryCount = new AtomicInteger(0); private static final AtomicLong ID_GENERATOR = new AtomicLong(0); @@ -199,11 +198,6 @@ public class InternalTestProtocolSession extends AMQProtocolEngine implements Pr } } - public boolean isClosed() - { - return _closed; - } - public void closeProtocolSession() { // Override as we don't have a real IOSession to close. diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/protocol/MaxChannelsTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/protocol/MaxChannelsTest.java index f6e83e6369..e8ee2c4d0b 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/protocol/MaxChannelsTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/protocol/MaxChannelsTest.java @@ -20,13 +20,12 @@ */ package org.apache.qpid.server.protocol; -import junit.framework.TestCase; import org.apache.qpid.AMQException; import org.apache.qpid.protocol.AMQConstant; import org.apache.qpid.server.AMQChannel; +import org.apache.qpid.server.registry.ApplicationRegistry; import org.apache.qpid.server.util.InternalBrokerBaseCase; import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.server.registry.ApplicationRegistry; /** Test class to test MBean operations for AMQMinaProtocolSession. */ public class MaxChannelsTest extends InternalBrokerBaseCase diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/protocol/MultiVersionProtocolEngineFactoryTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/protocol/MultiVersionProtocolEngineFactoryTest.java index 9d76d5efca..d8b5cd02cf 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/protocol/MultiVersionProtocolEngineFactoryTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/protocol/MultiVersionProtocolEngineFactoryTest.java @@ -20,11 +20,8 @@ */ package org.apache.qpid.server.protocol; -import java.nio.ByteBuffer; -import java.util.EnumSet; -import java.util.Set; - import org.apache.commons.configuration.XMLConfiguration; + import org.apache.qpid.protocol.ServerProtocolEngine; import org.apache.qpid.server.configuration.ServerConfiguration; import org.apache.qpid.server.registry.ApplicationRegistry; @@ -32,6 +29,10 @@ import org.apache.qpid.server.util.TestApplicationRegistry; import org.apache.qpid.test.utils.QpidTestCase; import org.apache.qpid.transport.TestNetworkConnection; +import java.nio.ByteBuffer; +import java.util.EnumSet; +import java.util.Set; + public class MultiVersionProtocolEngineFactoryTest extends QpidTestCase { protected void setUp() throws Exception @@ -120,10 +121,10 @@ public class MultiVersionProtocolEngineFactoryTest extends QpidTestCase Set versions = EnumSet.allOf(AmqpProtocolVersion.class); MultiVersionProtocolEngineFactory factory = - new MultiVersionProtocolEngineFactory("localhost", versions); + new MultiVersionProtocolEngineFactory(versions, null); //create a dummy to retrieve the 'current' ID number - long previousId = factory.newProtocolEngine(new TestNetworkConnection()).getConnectionId(); + long previousId = factory.newProtocolEngine().getConnectionId(); //create a protocol engine and send the AMQP header for all supported AMQP verisons, //ensuring the ID assigned increases as expected @@ -133,7 +134,9 @@ public class MultiVersionProtocolEngineFactoryTest extends QpidTestCase byte[] header = getAmqpHeader(version); assertNotNull("protocol header should not be null", header); - ServerProtocolEngine engine = factory.newProtocolEngine(new TestNetworkConnection()); + ServerProtocolEngine engine = factory.newProtocolEngine(); + TestNetworkConnection conn = new TestNetworkConnection(); + engine.setNetworkConnection(conn, conn.getSender()); assertEquals("ID did not increment as expected", expectedID, engine.getConnectionId()); //actually feed in the AMQP header for this protocol version, and ensure the ID remains consistent @@ -143,4 +146,24 @@ public class MultiVersionProtocolEngineFactoryTest extends QpidTestCase previousId = expectedID; } } + + /** + * Test to verify that when requesting a ProtocolEngineFactory to produce engines having a default reply to unsupported + * version initiations, there is enforcement that the default reply is itself a supported protocol version. + */ + public void testUnsupportedDefaultReplyCausesIllegalArgumentException() + { + Set versions = EnumSet.allOf(AmqpProtocolVersion.class); + versions.remove(AmqpProtocolVersion.v0_9); + + try + { + new MultiVersionProtocolEngineFactory(versions, AmqpProtocolVersion.v0_9); + fail("should not have been allowed to create the factory"); + } + catch(IllegalArgumentException iae) + { + //expected + } + } } diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/AMQPriorityQueueTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/AMQPriorityQueueTest.java index d5f8ef3d54..01a2178911 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/AMQPriorityQueueTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/AMQPriorityQueueTest.java @@ -20,14 +20,16 @@ package org.apache.qpid.server.queue; * */ -import java.util.ArrayList; import junit.framework.AssertionFailedError; + import org.apache.qpid.AMQException; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.framing.BasicContentHeaderProperties; import org.apache.qpid.framing.FieldTable; import org.apache.qpid.server.message.AMQMessage; +import java.util.ArrayList; + public class AMQPriorityQueueTest extends SimpleAMQQueueTest { diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueAlertTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueAlertTest.java index 47b8b7eb18..25d35aab16 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueAlertTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueAlertTest.java @@ -22,8 +22,8 @@ package org.apache.qpid.server.queue; import org.apache.qpid.AMQException; import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.ContentHeaderBody; import org.apache.qpid.framing.BasicContentHeaderProperties; +import org.apache.qpid.framing.ContentHeaderBody; import org.apache.qpid.framing.abstraction.ContentChunk; import org.apache.qpid.framing.abstraction.MessagePublishInfo; import org.apache.qpid.server.AMQChannel; @@ -35,6 +35,8 @@ import org.apache.qpid.server.subscription.SubscriptionFactoryImpl; import org.apache.qpid.server.util.InternalBrokerBaseCase; import javax.management.Notification; + +import java.nio.ByteBuffer; import java.util.ArrayList; /** This class tests all the alerts an AMQQueue can throw based on threshold values of different parameters */ @@ -277,7 +279,7 @@ public class AMQQueueAlertTest extends InternalBrokerBaseCase ContentHeaderBody contentHeaderBody = new ContentHeaderBody(); BasicContentHeaderProperties props = new BasicContentHeaderProperties(); contentHeaderBody.setProperties(props); - contentHeaderBody.bodySize = size; // in bytes + contentHeaderBody.setBodySize(size); // in bytes IncomingMessage message = new IncomingMessage(publish); message.setContentHeaderBody(contentHeaderBody); @@ -300,7 +302,7 @@ public class AMQQueueAlertTest extends InternalBrokerBaseCase messages[i] = message(false, size); ArrayList qs = new ArrayList(); qs.add(getQueue()); - metaData[i] = messages[i].headersReceived(); + metaData[i] = messages[i].headersReceived(System.currentTimeMillis()); messages[i].setStoredMessage(getMessageStore().addMessage(metaData[i])); messages[i].enqueue(qs); @@ -309,9 +311,9 @@ public class AMQQueueAlertTest extends InternalBrokerBaseCase for (int i = 0; i < messageCount; i++) { - messages[i].addContentBodyFrame(new ContentChunk(){ - - byte[] _data = new byte[(int)size]; + ContentChunk contentChunk = new ContentChunk() + { + private byte[] _data = new byte[(int)size]; public int getSize() { @@ -325,12 +327,13 @@ public class AMQQueueAlertTest extends InternalBrokerBaseCase public void reduceToFit() { - } - }); + }; - getQueue().enqueue(new AMQMessage(messages[i].getStoredMessage())); + messages[i].addContentBodyFrame(contentChunk); + messages[i].getStoredMessage().addContent(0, ByteBuffer.wrap(contentChunk.getData())); + getQueue().enqueue(new AMQMessage(messages[i].getStoredMessage())); } } diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueFactoryTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueFactoryTest.java index 2b7d1d7f26..337ff194c3 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueFactoryTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueFactoryTest.java @@ -21,6 +21,7 @@ package org.apache.qpid.server.queue; import org.apache.commons.configuration.XMLConfiguration; + import org.apache.qpid.AMQException; import org.apache.qpid.exchange.ExchangeDefaults; import org.apache.qpid.framing.AMQShortString; @@ -40,8 +41,8 @@ import org.apache.qpid.test.utils.QpidTestCase; public class AMQQueueFactoryTest extends QpidTestCase { - QueueRegistry _queueRegistry; - VirtualHost _virtualHost; + private QueueRegistry _queueRegistry; + private VirtualHost _virtualHost; @Override public void setUp() throws Exception diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueMBeanTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueMBeanTest.java index f70250132a..45933e7064 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueMBeanTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/AMQQueueMBeanTest.java @@ -21,30 +21,32 @@ package org.apache.qpid.server.queue; import org.apache.commons.lang.time.FastDateFormat; + import org.apache.qpid.AMQException; -import org.apache.qpid.framing.ContentHeaderBody; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.framing.BasicContentHeaderProperties; import org.apache.qpid.framing.ContentBody; +import org.apache.qpid.framing.ContentHeaderBody; +import org.apache.qpid.framing.abstraction.ContentChunk; import org.apache.qpid.framing.abstraction.MessagePublishInfo; import org.apache.qpid.management.common.mbeans.ManagedQueue; import org.apache.qpid.server.AMQChannel; -import org.apache.qpid.server.util.InternalBrokerBaseCase; import org.apache.qpid.server.message.AMQMessage; import org.apache.qpid.server.message.MessageMetaData; -import org.apache.qpid.server.subscription.Subscription; -import org.apache.qpid.server.subscription.SubscriptionFactory; -import org.apache.qpid.server.subscription.SubscriptionFactoryImpl; import org.apache.qpid.server.protocol.InternalTestProtocolSession; import org.apache.qpid.server.registry.ApplicationRegistry; import org.apache.qpid.server.store.TestableMemoryMessageStore; +import org.apache.qpid.server.subscription.Subscription; +import org.apache.qpid.server.subscription.SubscriptionFactory; +import org.apache.qpid.server.subscription.SubscriptionFactoryImpl; +import org.apache.qpid.server.util.InternalBrokerBaseCase; import javax.management.JMException; import javax.management.openmbean.CompositeData; import javax.management.openmbean.CompositeDataSupport; import javax.management.openmbean.TabularData; - import java.io.IOException; +import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; @@ -457,15 +459,16 @@ public class AMQQueueMBeanTest extends InternalBrokerBaseCase currentMessage.enqueue(qs); // route header - MessageMetaData mmd = currentMessage.headersReceived(); - currentMessage.setStoredMessage(getMessageStore().addMessage(mmd)); + MessageMetaData mmd = currentMessage.headersReceived(System.currentTimeMillis()); - // Add the body so we have something to test later - currentMessage.addContentBodyFrame( - getSession().getMethodRegistry() - .getProtocolVersionMethodConverter() - .convertToContentChunk( - new ContentBody(new byte[(int) MESSAGE_SIZE]))); + // Add the message to the store so we have something to test later + currentMessage.setStoredMessage(getMessageStore().addMessage(mmd)); + ContentChunk chunk = getSession().getMethodRegistry() + .getProtocolVersionMethodConverter() + .convertToContentChunk( + new ContentBody(new byte[(int) MESSAGE_SIZE])); + currentMessage.addContentBodyFrame(chunk); + currentMessage.getStoredMessage().addContent(0, ByteBuffer.wrap(chunk.getData())); AMQMessage m = new AMQMessage(currentMessage.getStoredMessage()); for(BaseQueue q : currentMessage.getDestinationQueues()) @@ -510,7 +513,7 @@ public class AMQQueueMBeanTest extends InternalBrokerBaseCase }; ContentHeaderBody contentHeaderBody = new ContentHeaderBody(); - contentHeaderBody.bodySize = MESSAGE_SIZE; // in bytes + contentHeaderBody.setBodySize(MESSAGE_SIZE); // in bytes final BasicContentHeaderProperties props = new BasicContentHeaderProperties(); contentHeaderBody.setProperties(props); props.setDeliveryMode((byte) (persistent ? 2 : 1)); diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/AckTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/AckTest.java index 5d559c9d0d..273f0dc018 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/AckTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/AckTest.java @@ -20,30 +20,30 @@ */ package org.apache.qpid.server.queue; -import junit.framework.TestCase; import org.apache.log4j.Logger; + import org.apache.qpid.AMQException; +import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.framing.BasicContentHeaderProperties; import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.framing.abstraction.MessagePublishInfo; import org.apache.qpid.server.AMQChannel; +import org.apache.qpid.server.ack.UnacknowledgedMessageMap; +import org.apache.qpid.server.flow.LimitlessCreditManager; +import org.apache.qpid.server.flow.Pre0_10CreditManager; import org.apache.qpid.server.message.AMQMessage; import org.apache.qpid.server.message.MessageMetaData; +import org.apache.qpid.server.protocol.AMQProtocolSession; +import org.apache.qpid.server.protocol.InternalTestProtocolSession; +import org.apache.qpid.server.registry.ApplicationRegistry; import org.apache.qpid.server.store.StoredMessage; -import org.apache.qpid.server.txn.ServerTransaction; +import org.apache.qpid.server.store.TestMemoryMessageStore; +import org.apache.qpid.server.subscription.Subscription; +import org.apache.qpid.server.subscription.SubscriptionFactoryImpl; import org.apache.qpid.server.txn.AutoCommitTransaction; +import org.apache.qpid.server.txn.ServerTransaction; import org.apache.qpid.server.util.InternalBrokerBaseCase; import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.server.protocol.InternalTestProtocolSession; -import org.apache.qpid.server.protocol.AMQProtocolSession; -import org.apache.qpid.server.subscription.Subscription; -import org.apache.qpid.server.subscription.SubscriptionFactoryImpl; -import org.apache.qpid.server.flow.LimitlessCreditManager; -import org.apache.qpid.server.flow.Pre0_10CreditManager; -import org.apache.qpid.server.ack.UnacknowledgedMessageMap; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.store.TestMemoryMessageStore; import java.util.ArrayList; import java.util.Set; @@ -143,7 +143,7 @@ public class AckTest extends InternalBrokerBaseCase ArrayList qs = new ArrayList(); qs.add(_queue); msg.enqueue(qs); - MessageMetaData mmd = msg.headersReceived(); + MessageMetaData mmd = msg.headersReceived(System.currentTimeMillis()); final StoredMessage storedMessage = _messageStore.addMessage(mmd); msg.setStoredMessage(storedMessage); final AMQMessage message = new AMQMessage(storedMessage); diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/MockAMQQueue.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/MockAMQQueue.java index f97ac5659e..afaa417415 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/MockAMQQueue.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/MockAMQQueue.java @@ -20,24 +20,25 @@ */ package org.apache.qpid.server.queue; +import org.apache.qpid.AMQException; import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.server.configuration.*; +import org.apache.qpid.server.binding.Binding; +import org.apache.qpid.server.configuration.ConfigStore; +import org.apache.qpid.server.configuration.ConfiguredObject; +import org.apache.qpid.server.configuration.QueueConfigType; import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin; import org.apache.qpid.server.exchange.Exchange; import org.apache.qpid.server.logging.LogSubject; -import org.apache.qpid.server.subscription.Subscription; -import org.apache.qpid.server.virtualhost.VirtualHost; import org.apache.qpid.server.management.ManagedObject; import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.security.AuthorizationHolder; import org.apache.qpid.server.protocol.AMQSessionModel; -import org.apache.qpid.server.binding.Binding; -import org.apache.qpid.server.txn.ServerTransaction; -import org.apache.qpid.AMQException; +import org.apache.qpid.server.security.AuthorizationHolder; +import org.apache.qpid.server.subscription.Subscription; +import org.apache.qpid.server.virtualhost.VirtualHost; import java.util.List; -import java.util.Set; import java.util.Map; +import java.util.Set; import java.util.UUID; import java.util.concurrent.CopyOnWriteArrayList; @@ -355,12 +356,12 @@ public class MockAMQQueue implements AMQQueue return null; } - public void moveMessagesToAnotherQueue(long fromMessageId, long toMessageId, String queueName, ServerTransaction storeContext) + public void moveMessagesToAnotherQueue(long fromMessageId, long toMessageId, String queueName) { } - public void copyMessagesToAnotherQueue(long fromMessageId, long toMessageId, String queueName, ServerTransaction storeContext) + public void copyMessagesToAnotherQueue(long fromMessageId, long toMessageId, String queueName) { } diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/MockMessagePublishInfo.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/MockMessagePublishInfo.java index 5a5ffaa14d..bcf4c7efc6 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/MockMessagePublishInfo.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/MockMessagePublishInfo.java @@ -20,8 +20,8 @@ */ package org.apache.qpid.server.queue; -import org.apache.qpid.framing.abstraction.MessagePublishInfo; import org.apache.qpid.framing.AMQShortString; +import org.apache.qpid.framing.abstraction.MessagePublishInfo; public class MockMessagePublishInfo implements MessagePublishInfo { diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/MockQueueEntry.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/MockQueueEntry.java index 7ad002c248..b3482f0599 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/MockQueueEntry.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/MockQueueEntry.java @@ -21,10 +21,10 @@ package org.apache.qpid.server.queue; import org.apache.qpid.AMQException; -import org.apache.qpid.server.subscription.Subscription; -import org.apache.qpid.server.message.AMQMessageHeader; import org.apache.qpid.server.message.AMQMessage; +import org.apache.qpid.server.message.AMQMessageHeader; import org.apache.qpid.server.message.ServerMessage; +import org.apache.qpid.server.subscription.Subscription; public class MockQueueEntry implements QueueEntry { diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/MockStoredMessage.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/MockStoredMessage.java index b4f8c6d07a..205dbf2e36 100755 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/MockStoredMessage.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/MockStoredMessage.java @@ -20,14 +20,13 @@ */ package org.apache.qpid.server.queue; +import org.apache.qpid.framing.BasicContentHeaderProperties; +import org.apache.qpid.framing.ContentHeaderBody; import org.apache.qpid.framing.FieldTable; - +import org.apache.qpid.framing.abstraction.MessagePublishInfo; +import org.apache.qpid.server.message.MessageMetaData; import org.apache.qpid.server.store.MessageStore; import org.apache.qpid.server.store.StoredMessage; -import org.apache.qpid.server.message.MessageMetaData; -import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.BasicContentHeaderProperties; -import org.apache.qpid.framing.abstraction.MessagePublishInfo; import java.nio.ByteBuffer; diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/QueueEntryImplTestBase.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/QueueEntryImplTestBase.java index d336132316..8be6061b45 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/QueueEntryImplTestBase.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/QueueEntryImplTestBase.java @@ -18,14 +18,16 @@ */ package org.apache.qpid.server.queue; -import java.lang.reflect.Field; import junit.framework.TestCase; + import org.apache.qpid.AMQException; import org.apache.qpid.server.message.AMQMessage; import org.apache.qpid.server.queue.QueueEntry.EntryState; import org.apache.qpid.server.subscription.MockSubscription; import org.apache.qpid.server.subscription.Subscription; +import java.lang.reflect.Field; + /** * Tests for {@link QueueEntryImpl} */ diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/QueueEntryListTestBase.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/QueueEntryListTestBase.java index cf910208e7..4b40c3b552 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/QueueEntryListTestBase.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/QueueEntryListTestBase.java @@ -20,6 +20,7 @@ package org.apache.qpid.server.queue; import junit.framework.TestCase; + import org.apache.qpid.AMQException; import org.apache.qpid.server.message.ServerMessage; @@ -30,6 +31,7 @@ public abstract class QueueEntryListTestBase extends TestCase { protected static final AMQQueue _testQueue = new MockAMQQueue("test"); public abstract QueueEntryList getTestList(); + public abstract QueueEntryList getTestList(boolean newList); public abstract long getExpectedFirstMsgId(); public abstract int getExpectedListLength(); public abstract ServerMessage getTestMessageToAdd() throws AMQException; @@ -187,4 +189,36 @@ public abstract class QueueEntryListTestBase extends TestCase .getMessage().getMessageNumber(), third.getMessage().getMessageNumber()); } + /** + * Tests that after the last node of the list is marked deleted but has not yet been removed, + * the iterator still ignores it and returns that it is 'atTail()' and can't 'advance()' + * + * @see QueueEntryListTestBase#getTestList() + * @see QueueEntryListTestBase#getExpectedListLength() + */ + public void testIteratorIgnoresDeletedFinalNode() throws Exception + { + QueueEntryList list = getTestList(true); + int i = 0; + + QueueEntry queueEntry1 = list.add(new MockAMQMessage(i++)); + QueueEntry queueEntry2 = list.add(new MockAMQMessage(i++)); + + assertSame(queueEntry2, list.next(queueEntry1)); + assertNull(list.next(queueEntry2)); + + //'delete' the 2nd QueueEntry + assertTrue("Deleting node should have succeeded", queueEntry2.delete()); + + QueueEntryIterator iter = list.iterator(); + + //verify the iterator isn't 'atTail', can advance, and returns the 1st QueueEntry + assertFalse("Iterator should not have been 'atTail'", iter.atTail()); + assertTrue("Iterator should have been able to advance", iter.advance()); + assertSame("Iterator returned unexpected QueueEntry", queueEntry1, iter.getNode()); + + //verify the iterator is atTail() and can't advance + assertTrue("Iterator should have been 'atTail'", iter.atTail()); + assertFalse("Iterator should not have been able to advance", iter.advance()); + } } diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/SelfValidatingSortedQueueEntryList.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/SelfValidatingSortedQueueEntryList.java index 7ff693e4c4..674af36b77 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/SelfValidatingSortedQueueEntryList.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/SelfValidatingSortedQueueEntryList.java @@ -20,6 +20,7 @@ package org.apache.qpid.server.queue; import junit.framework.Assert; + import org.apache.qpid.server.message.ServerMessage; import org.apache.qpid.server.queue.SortedQueueEntryImpl.Colour; diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleAMQQueueTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleAMQQueueTest.java index 28d52f4fd1..79c744902d 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleAMQQueueTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleAMQQueueTest.java @@ -21,12 +21,8 @@ package org.apache.qpid.server.queue; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; import org.apache.commons.configuration.PropertiesConfiguration; + import org.apache.qpid.AMQException; import org.apache.qpid.AMQInternalException; import org.apache.qpid.AMQSecurityException; @@ -49,12 +45,17 @@ import org.apache.qpid.server.store.TestableMemoryMessageStore; import org.apache.qpid.server.subscription.MockSubscription; import org.apache.qpid.server.subscription.Subscription; import org.apache.qpid.server.txn.AutoCommitTransaction; -import org.apache.qpid.server.txn.LocalTransaction; import org.apache.qpid.server.txn.ServerTransaction; import org.apache.qpid.server.util.InternalBrokerBaseCase; import org.apache.qpid.server.virtualhost.VirtualHost; import org.apache.qpid.server.virtualhost.VirtualHostImpl; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + public class SimpleAMQQueueTest extends InternalBrokerBaseCase { @@ -68,7 +69,7 @@ public class SimpleAMQQueueTest extends InternalBrokerBaseCase protected MockSubscription _subscription = new MockSubscription(); protected FieldTable _arguments = null; - MessagePublishInfo info = new MessagePublishInfo() + private MessagePublishInfo info = new MessagePublishInfo() { public AMQShortString getExchange() @@ -196,7 +197,7 @@ public class SimpleAMQQueueTest extends InternalBrokerBaseCase { } assertEquals(messageA, _subscription.getQueueContext().getLastSeenEntry().getMessage()); - assertNull(((QueueContext)_subscription.getQueueContext())._releasedEntry); + assertNull(((QueueContext)_subscription.getQueueContext()).getReleasedEntry()); // Check removing the subscription removes it's information from the queue _queue.unregisterSubscription(_subscription); @@ -218,7 +219,7 @@ public class SimpleAMQQueueTest extends InternalBrokerBaseCase _queue.registerSubscription(_subscription, false); Thread.sleep(150); assertEquals(messageA, _subscription.getQueueContext().getLastSeenEntry().getMessage()); - assertNull("There should be no releasedEntry after an enqueue", ((QueueContext)_subscription.getQueueContext())._releasedEntry); + assertNull("There should be no releasedEntry after an enqueue", ((QueueContext)_subscription.getQueueContext()).getReleasedEntry()); } /** @@ -233,7 +234,7 @@ public class SimpleAMQQueueTest extends InternalBrokerBaseCase _queue.registerSubscription(_subscription, false); Thread.sleep(150); assertEquals(messageB, _subscription.getQueueContext().getLastSeenEntry().getMessage()); - assertNull("There should be no releasedEntry after enqueues", ((QueueContext)_subscription.getQueueContext())._releasedEntry); + assertNull("There should be no releasedEntry after enqueues", ((QueueContext)_subscription.getQueueContext()).getReleasedEntry()); } /** @@ -280,7 +281,7 @@ public class SimpleAMQQueueTest extends InternalBrokerBaseCase assertTrue("Redelivery flag should now be set", queueEntries.get(0).isRedelivered()); assertFalse("Redelivery flag should remain be unset", queueEntries.get(1).isRedelivered()); assertFalse("Redelivery flag should remain be unset",queueEntries.get(2).isRedelivered()); - assertNull("releasedEntry should be cleared after requeue processed", ((QueueContext)_subscription.getQueueContext())._releasedEntry); + assertNull("releasedEntry should be cleared after requeue processed", ((QueueContext)_subscription.getQueueContext()).getReleasedEntry()); } /** @@ -324,7 +325,7 @@ public class SimpleAMQQueueTest extends InternalBrokerBaseCase assertTrue("Expecting the queue entry to be now expired", queueEntries.get(0).expired()); assertEquals("Total number of messages sent should not have changed", 1, _subscription.getMessages().size()); assertFalse("Redelivery flag should not be set", queueEntries.get(0).isRedelivered()); - assertNull("releasedEntry should be cleared after requeue processed", ((QueueContext)_subscription.getQueueContext())._releasedEntry); + assertNull("releasedEntry should be cleared after requeue processed", ((QueueContext)_subscription.getQueueContext()).getReleasedEntry()); } @@ -375,7 +376,7 @@ public class SimpleAMQQueueTest extends InternalBrokerBaseCase assertTrue("Redelivery flag should now be set", queueEntries.get(0).isRedelivered()); assertFalse("Redelivery flag should remain be unset", queueEntries.get(1).isRedelivered()); assertTrue("Redelivery flag should now be set",queueEntries.get(2).isRedelivered()); - assertNull("releasedEntry should be cleared after requeue processed", ((QueueContext)_subscription.getQueueContext())._releasedEntry); + assertNull("releasedEntry should be cleared after requeue processed", ((QueueContext)_subscription.getQueueContext()).getReleasedEntry()); } @@ -418,8 +419,8 @@ public class SimpleAMQQueueTest extends InternalBrokerBaseCase Thread.sleep(150); // Work done by SubFlushRunner/QueueRunner Threads assertEquals("Unexpected total number of messages sent to both subscriptions after release", 3, subscription1.getMessages().size() + subscription2.getMessages().size()); - assertNull("releasedEntry should be cleared after requeue processed", ((QueueContext)subscription1.getQueueContext())._releasedEntry); - assertNull("releasedEntry should be cleared after requeue processed", ((QueueContext)subscription2.getQueueContext())._releasedEntry); + assertNull("releasedEntry should be cleared after requeue processed", ((QueueContext)subscription1.getQueueContext()).getReleasedEntry()); + assertNull("releasedEntry should be cleared after requeue processed", ((QueueContext)subscription2.getQueueContext()).getReleasedEntry()); } public void testExclusiveConsumer() throws AMQException @@ -632,7 +633,7 @@ public class SimpleAMQQueueTest extends InternalBrokerBaseCase // Send persistent message qs.add(_queue); - MessageMetaData metaData = msg.headersReceived(); + MessageMetaData metaData = msg.headersReceived(System.currentTimeMillis()); StoredMessage handle = _store.addMessage(metaData); msg.setStoredMessage(handle); @@ -837,7 +838,7 @@ public class SimpleAMQQueueTest extends InternalBrokerBaseCase /** * Tests that dequeued message is not copied as part of invocation of - * {@link SimpleAMQQueue#copyMessagesToAnotherQueue(long, long, String, ServerTransaction)} + * {@link SimpleAMQQueue#copyMessagesToAnotherQueue(long, long, String)} */ public void testCopyMessagesWithDequeuedEntry() { @@ -854,14 +855,8 @@ public class SimpleAMQQueueTest extends InternalBrokerBaseCase // create another queue SimpleAMQQueue queue = createQueue(anotherQueueName); - // create transaction - ServerTransaction txn = new LocalTransaction(_queue.getVirtualHost().getMessageStore()); - // copy messages into another queue - _queue.copyMessagesToAnotherQueue(0, messageNumber, anotherQueueName, txn); - - // commit transaction - txn.commit(); + _queue.copyMessagesToAnotherQueue(0, messageNumber, anotherQueueName); // get messages on another queue List entries = queue.getMessagesOnTheQueue(); @@ -887,7 +882,7 @@ public class SimpleAMQQueueTest extends InternalBrokerBaseCase /** * Tests that dequeued message is not moved as part of invocation of - * {@link SimpleAMQQueue#moveMessagesToAnotherQueue(long, long, String, ServerTransaction)} + * {@link SimpleAMQQueue#moveMessagesToAnotherQueue(long, long, String)} */ public void testMovedMessagesWithDequeuedEntry() { @@ -904,14 +899,8 @@ public class SimpleAMQQueueTest extends InternalBrokerBaseCase // create another queue SimpleAMQQueue queue = createQueue(anotherQueueName); - // create transaction - ServerTransaction txn = new LocalTransaction(_queue.getVirtualHost().getMessageStore()); - // move messages into another queue - _queue.moveMessagesToAnotherQueue(0, messageNumber, anotherQueueName, txn); - - // commit transaction - txn.commit(); + _queue.moveMessagesToAnotherQueue(0, messageNumber, anotherQueueName); // get messages on another queue List entries = queue.getMessagesOnTheQueue(); @@ -1183,6 +1172,62 @@ public class SimpleAMQQueueTest extends InternalBrokerBaseCase ((AMQMessage) messages.get(1).getMessage()).getMessageId()); } + public void testActiveConsumerCount() throws Exception + { + final SimpleAMQQueue queue = new SimpleAMQQueue(new AMQShortString("testActiveConsumerCount"), false, new AMQShortString("testOwner"), + false, false, _virtualHost, new SimpleQueueEntryList.Factory(), null); + + //verify adding an active subscription increases the count + final MockSubscription subscription1 = new MockSubscription(); + subscription1.setActive(true); + assertEquals("Unexpected active consumer count", 0, queue.getActiveConsumerCount()); + queue.registerSubscription(subscription1, false); + assertEquals("Unexpected active consumer count", 1, queue.getActiveConsumerCount()); + + //verify adding an inactive subscription doesn't increase the count + final MockSubscription subscription2 = new MockSubscription(); + subscription2.setActive(false); + assertEquals("Unexpected active consumer count", 1, queue.getActiveConsumerCount()); + queue.registerSubscription(subscription2, false); + assertEquals("Unexpected active consumer count", 1, queue.getActiveConsumerCount()); + + //verify behaviour in face of expected state changes: + + //verify a subscription going suspended->active increases the count + queue.stateChange(subscription2, Subscription.State.SUSPENDED, Subscription.State.ACTIVE); + assertEquals("Unexpected active consumer count", 2, queue.getActiveConsumerCount()); + + //verify a subscription going active->suspended decreases the count + queue.stateChange(subscription2, Subscription.State.ACTIVE, Subscription.State.SUSPENDED); + assertEquals("Unexpected active consumer count", 1, queue.getActiveConsumerCount()); + + //verify a subscription going suspended->closed doesn't change the count + queue.stateChange(subscription2, Subscription.State.SUSPENDED, Subscription.State.CLOSED); + assertEquals("Unexpected active consumer count", 1, queue.getActiveConsumerCount()); + + //verify a subscription going active->closed decreases the count + queue.stateChange(subscription2, Subscription.State.ACTIVE, Subscription.State.CLOSED); + assertEquals("Unexpected active consumer count", 0, queue.getActiveConsumerCount()); + + //verify behaviour in face of unexpected state changes: + + //verify a subscription going closed->active increases the count + queue.stateChange(subscription2, Subscription.State.CLOSED, Subscription.State.ACTIVE); + assertEquals("Unexpected active consumer count", 1, queue.getActiveConsumerCount()); + + //verify a subscription going active->active doesn't change the count + queue.stateChange(subscription2, Subscription.State.ACTIVE, Subscription.State.ACTIVE); + assertEquals("Unexpected active consumer count", 1, queue.getActiveConsumerCount()); + + //verify a subscription going closed->suspended doesn't change the count + queue.stateChange(subscription2, Subscription.State.CLOSED, Subscription.State.SUSPENDED); + assertEquals("Unexpected active consumer count", 1, queue.getActiveConsumerCount()); + + //verify a subscription going suspended->suspended doesn't change the count + queue.stateChange(subscription2, Subscription.State.SUSPENDED, Subscription.State.SUSPENDED); + assertEquals("Unexpected active consumer count", 1, queue.getActiveConsumerCount()); + } + /** * A helper method to create a queue with given name * diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleAMQQueueThreadPoolTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleAMQQueueThreadPoolTest.java index a40dc5670f..39ddd1d500 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleAMQQueueThreadPoolTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleAMQQueueThreadPoolTest.java @@ -20,15 +20,13 @@ */ package org.apache.qpid.server.queue; -import junit.framework.TestCase; +import org.apache.qpid.AMQException; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.pool.ReferenceCountingExecutorService; +import org.apache.qpid.server.registry.ApplicationRegistry; import org.apache.qpid.server.util.InternalBrokerBaseCase; import org.apache.qpid.server.virtualhost.VirtualHost; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.AMQException; - public class SimpleAMQQueueThreadPoolTest extends InternalBrokerBaseCase { diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleQueueEntryListTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleQueueEntryListTest.java index a873739ca7..caf1eea09f 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleQueueEntryListTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/SimpleQueueEntryListTest.java @@ -20,18 +20,20 @@ */ package org.apache.qpid.server.queue; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; import org.apache.qpid.AMQException; import org.apache.qpid.server.message.AMQMessage; import org.apache.qpid.server.message.ServerMessage; +import org.apache.qpid.server.queue.SimpleQueueEntryList.QueueEntryIteratorImpl; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; public class SimpleQueueEntryListTest extends QueueEntryListTestBase { private SimpleQueueEntryList _sqel; private static final String SCAVENGE_PROP = "qpid.queue.scavenge_count"; - String oldScavengeValue = null; + private String oldScavengeValue = null; @Override protected void setUp() @@ -58,11 +60,24 @@ public class SimpleQueueEntryListTest extends QueueEntryListTestBase System.clearProperty(SCAVENGE_PROP); } } - + @Override public QueueEntryList getTestList() { - return _sqel; + return getTestList(false); + } + + @Override + public QueueEntryList getTestList(boolean newList) + { + if(newList) + { + return new SimpleQueueEntryList(_testQueue); + } + else + { + return _sqel; + } } @Override @@ -215,5 +230,4 @@ public class SimpleQueueEntryListTest extends QueueEntryListTestBase next = next.getNextValidEntry(); assertNull("The next entry after the last should be null", next); } - } diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/SortedQueueEntryListTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/SortedQueueEntryListTest.java index d177993886..38b12f8250 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/SortedQueueEntryListTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/queue/SortedQueueEntryListTest.java @@ -19,11 +19,11 @@ */ package org.apache.qpid.server.queue; +import org.apache.qpid.AMQException; import org.apache.qpid.server.message.AMQMessage; +import org.apache.qpid.server.message.ServerMessage; import java.util.Arrays; -import org.apache.qpid.AMQException; -import org.apache.qpid.server.message.ServerMessage; public class SortedQueueEntryListTest extends QueueEntryListTestBase { @@ -77,9 +77,23 @@ public class SortedQueueEntryListTest extends QueueEntryListTestBase } + @Override public QueueEntryList getTestList() { - return _sqel; + return getTestList(false); + } + + @Override + public QueueEntryList getTestList(boolean newList) + { + if(newList) + { + return new SelfValidatingSortedQueueEntryList(_testQueue, "KEY"); + } + else + { + return _sqel; + } } public int getExpectedListLength() diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/registry/ApplicationRegistryShutdownTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/registry/ApplicationRegistryShutdownTest.java index e45c8d7b96..9ff8f0a531 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/registry/ApplicationRegistryShutdownTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/registry/ApplicationRegistryShutdownTest.java @@ -22,10 +22,10 @@ package org.apache.qpid.server.registry; import org.apache.qpid.server.util.InternalBrokerBaseCase; -import java.security.Security; import java.security.Provider; -import java.util.List; +import java.security.Security; import java.util.LinkedList; +import java.util.List; /** * QPID-1390 : Test to validate that the AuthenticationManger can successfully unregister any new SASL providers when @@ -36,7 +36,7 @@ import java.util.LinkedList; public class ApplicationRegistryShutdownTest extends InternalBrokerBaseCase { - Provider[] _defaultProviders; + private Provider[] _defaultProviders; @Override public void setUp() throws Exception { @@ -80,11 +80,10 @@ public class ApplicationRegistryShutdownTest extends InternalBrokerBaseCase } } - // Not using isEmpty as that is not in Java 5 - assertTrue("No new SASL mechanisms added by initialisation.", additions.size() != 0 ); + assertFalse("No new SASL mechanisms added by initialisation.", additions.isEmpty()); //Close the registry which will perform the close the AuthenticationManager - getRegistry().close(); + stopBroker(); //Validate that the SASL plugFins have been removed. Provider[] providersAfterClose = Security.getProviders(); diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/Base64MD5PasswordFilePrincipalDatabaseTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/Base64MD5PasswordFilePrincipalDatabaseTest.java index 2ab15d4872..33740af1e7 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/Base64MD5PasswordFilePrincipalDatabaseTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/Base64MD5PasswordFilePrincipalDatabaseTest.java @@ -21,13 +21,12 @@ package org.apache.qpid.server.security.auth.database; import junit.framework.TestCase; - -import javax.security.auth.callback.PasswordCallback; -import javax.security.auth.login.AccountNotFoundException; - import org.apache.commons.codec.binary.Base64; + import org.apache.qpid.server.security.auth.sasl.UsernamePrincipal; +import javax.security.auth.callback.PasswordCallback; +import javax.security.auth.login.AccountNotFoundException; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/HashedUserTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/HashedUserTest.java index aa85cac758..abb0b15a76 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/HashedUserTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/HashedUserTest.java @@ -21,8 +21,6 @@ package org.apache.qpid.server.security.auth.database; import junit.framework.TestCase; -import org.apache.log4j.Level; -import org.apache.log4j.Logger; import java.io.UnsupportedEncodingException; @@ -32,9 +30,9 @@ import java.io.UnsupportedEncodingException; public class HashedUserTest extends TestCase { - String USERNAME = "username"; - String PASSWORD = "password"; - String B64_ENCODED_PASSWORD = "cGFzc3dvcmQ="; + private String USERNAME = "username"; + private String PASSWORD = "password"; + private String B64_ENCODED_PASSWORD = "cGFzc3dvcmQ="; public void testToLongArrayConstructor() { @@ -47,49 +45,39 @@ public class HashedUserTest extends TestCase { assertEquals("User Data should be length 2, username, password", e.getMessage()); } - catch (UnsupportedEncodingException e) - { - fail(e.getMessage()); - } + } public void testArrayConstructor() { - try - { - HashedUser user = new HashedUser(new String[]{USERNAME, B64_ENCODED_PASSWORD}); - assertEquals("Username incorrect", USERNAME, user.getName()); - int index = 0; - - char[] hash = B64_ENCODED_PASSWORD.toCharArray(); - - try - { - for (byte c : user.getEncodedPassword()) - { - assertEquals("Password incorrect", hash[index], (char) c); - index++; - } - } - catch (Exception e) - { - fail(e.getMessage()); - } + HashedUser user = new HashedUser(new String[]{USERNAME, B64_ENCODED_PASSWORD}); + assertEquals("Username incorrect", USERNAME, user.getName()); + int index = 0; - hash = PASSWORD.toCharArray(); + char[] hash = B64_ENCODED_PASSWORD.toCharArray(); - index=0; - for (char c : user.getPassword()) + try + { + for (byte c : user.getEncodedPassword()) { - assertEquals("Password incorrect", hash[index], c); + assertEquals("Password incorrect", hash[index], (char) c); index++; } - } - catch (UnsupportedEncodingException e) + catch (Exception e) { fail(e.getMessage()); } + + hash = PASSWORD.toCharArray(); + + index=0; + for (char c : user.getPassword()) + { + assertEquals("Password incorrect", hash[index], c); + index++; + } + } } diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/PlainPasswordFilePrincipalDatabaseTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/PlainPasswordFilePrincipalDatabaseTest.java index a3dad19bb4..b8601f0e5c 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/PlainPasswordFilePrincipalDatabaseTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/PlainPasswordFilePrincipalDatabaseTest.java @@ -22,10 +22,9 @@ package org.apache.qpid.server.security.auth.database; import junit.framework.TestCase; -import javax.security.auth.login.AccountNotFoundException; - import org.apache.qpid.server.security.auth.sasl.UsernamePrincipal; +import javax.security.auth.login.AccountNotFoundException; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/PlainUserTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/PlainUserTest.java index 7f0843d46e..44faa57dbe 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/PlainUserTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/database/PlainUserTest.java @@ -28,8 +28,8 @@ import junit.framework.TestCase; public class PlainUserTest extends TestCase { - String USERNAME = "username"; - String PASSWORD = "password"; + private String USERNAME = "username"; + private String PASSWORD = "password"; public void testTooLongArrayConstructor() { @@ -54,7 +54,7 @@ public class PlainUserTest extends TestCase try { - for (byte c : user.getPasswordBytes()) + for (byte c : user.getEncodedPassword()) { assertEquals("Password incorrect", password[index], (char) c); index++; diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/PrincipalDatabaseAuthenticationManagerTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/PrincipalDatabaseAuthenticationManagerTest.java index b10442d7db..1a42fe3886 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/PrincipalDatabaseAuthenticationManagerTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/manager/PrincipalDatabaseAuthenticationManagerTest.java @@ -20,20 +20,10 @@ */ package org.apache.qpid.server.security.auth.manager; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileWriter; -import java.security.Provider; -import java.security.Security; - -import javax.security.auth.Subject; -import javax.security.sasl.SaslException; -import javax.security.sasl.SaslServer; - import org.apache.commons.configuration.CompositeConfiguration; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.XMLConfiguration; + import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin; import org.apache.qpid.server.security.auth.AuthenticationResult; import org.apache.qpid.server.security.auth.AuthenticationResult.AuthenticationStatus; @@ -41,6 +31,16 @@ import org.apache.qpid.server.security.auth.database.PlainPasswordFilePrincipalD import org.apache.qpid.server.security.auth.sasl.UsernamePrincipal; import org.apache.qpid.server.util.InternalBrokerBaseCase; +import javax.security.auth.Subject; +import javax.security.sasl.SaslException; +import javax.security.sasl.SaslServer; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileWriter; +import java.security.Provider; +import java.security.Security; + /** * * Tests the public methods of PrincipalDatabaseAuthenticationManager. diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/rmi/RMIPasswordAuthenticatorTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/rmi/RMIPasswordAuthenticatorTest.java index f356673598..0163533ae9 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/rmi/RMIPasswordAuthenticatorTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/rmi/RMIPasswordAuthenticatorTest.java @@ -20,13 +20,6 @@ */ package org.apache.qpid.server.security.auth.rmi; -import java.util.Collections; - -import javax.management.remote.JMXPrincipal; -import javax.security.auth.Subject; -import javax.security.sasl.SaslException; -import javax.security.sasl.SaslServer; - import junit.framework.TestCase; import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin; @@ -34,6 +27,12 @@ import org.apache.qpid.server.security.auth.AuthenticationResult; import org.apache.qpid.server.security.auth.AuthenticationResult.AuthenticationStatus; import org.apache.qpid.server.security.auth.manager.AuthenticationManager; +import javax.management.remote.JMXPrincipal; +import javax.security.auth.Subject; +import javax.security.sasl.SaslException; +import javax.security.sasl.SaslServer; +import java.util.Collections; + /** * Tests the RMIPasswordAuthenticator and its collaboration with the AuthenticationManager. * diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/CRAMMD5HexInitialiserTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/CRAMMD5HexInitialiserTest.java index 3c5ed1d6c2..e408fd73d5 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/CRAMMD5HexInitialiserTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/CRAMMD5HexInitialiserTest.java @@ -21,6 +21,7 @@ package org.apache.qpid.server.security.auth.sasl; import junit.framework.TestCase; + import org.apache.qpid.server.security.auth.database.PropertiesPrincipalDatabase; import org.apache.qpid.server.security.auth.sasl.crammd5.CRAMMD5HexInitialiser; diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/CRAMMD5HexServerTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/CRAMMD5HexServerTest.java index 86e4e23750..51c2a0a5b8 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/CRAMMD5HexServerTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/CRAMMD5HexServerTest.java @@ -21,25 +21,24 @@ package org.apache.qpid.server.security.auth.sasl; -import java.io.File; -import java.io.IOException; -import java.security.MessageDigest; -import java.security.Principal; - -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; -import javax.security.auth.login.AccountNotFoundException; -import javax.security.sasl.SaslException; -import javax.security.sasl.SaslServer; - import junit.framework.TestCase; - import org.apache.commons.codec.binary.Hex; + import org.apache.qpid.server.security.auth.database.Base64MD5PasswordFilePrincipalDatabase; import org.apache.qpid.server.security.auth.sasl.crammd5.CRAMMD5HexInitialiser; import org.apache.qpid.server.security.auth.sasl.crammd5.CRAMMD5HexSaslServer; import org.apache.qpid.server.security.auth.sasl.crammd5.CRAMMD5HexServerFactory; +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import javax.security.auth.login.AccountNotFoundException; +import javax.security.sasl.SaslException; +import javax.security.sasl.SaslServer; +import java.io.File; +import java.io.IOException; +import java.security.MessageDigest; +import java.security.Principal; + /** * Test for the CRAM-MD5-HEX SASL mechanism. * diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/SaslServerTestCase.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/SaslServerTestCase.java index f80413d4f8..f5247634ac 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/SaslServerTestCase.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/SaslServerTestCase.java @@ -21,12 +21,12 @@ package org.apache.qpid.server.security.auth.sasl; -import javax.security.sasl.SaslException; -import javax.security.sasl.SaslServer; +import junit.framework.TestCase; import org.apache.qpid.server.security.auth.database.PrincipalDatabase; -import junit.framework.TestCase; +import javax.security.sasl.SaslException; +import javax.security.sasl.SaslServer; public abstract class SaslServerTestCase extends TestCase { @@ -54,7 +54,7 @@ public abstract class SaslServerTestCase extends TestCase } catch (SaslException e) { - assertEquals("Authentication failed", e.getCause().getMessage()); + assertTrue(e.getMessage().contains("Authentication failed")); exceptionCaught = true; } if (!exceptionCaught) diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/TestPrincipalDatabase.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/TestPrincipalDatabase.java index 8507e49e17..8c7f3ad6ef 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/TestPrincipalDatabase.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/TestPrincipalDatabase.java @@ -21,17 +21,15 @@ package org.apache.qpid.server.security.auth.sasl; +import org.apache.qpid.server.security.auth.database.PrincipalDatabase; + +import javax.security.auth.callback.PasswordCallback; +import javax.security.auth.login.AccountNotFoundException; import java.io.IOException; import java.security.Principal; import java.util.List; import java.util.Map; -import javax.security.auth.callback.PasswordCallback; -import javax.security.auth.login.AccountNotFoundException; - -import org.apache.qpid.server.security.auth.database.PrincipalDatabase; -import org.apache.qpid.server.security.auth.sasl.AuthenticationProviderInitialiser; - public class TestPrincipalDatabase implements PrincipalDatabase { diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/TestPrincipalUtils.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/TestPrincipalUtils.java index 8b9b2df5a3..7ce03eaa79 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/TestPrincipalUtils.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/TestPrincipalUtils.java @@ -20,13 +20,12 @@ */ package org.apache.qpid.server.security.auth.sasl; +import javax.security.auth.Subject; import java.security.Principal; import java.util.Collections; import java.util.HashSet; import java.util.Set; -import javax.security.auth.Subject; - public class TestPrincipalUtils { diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/UsernamePrincipalTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/UsernamePrincipalTest.java index 541f14d923..75bc76c688 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/UsernamePrincipalTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/security/auth/sasl/UsernamePrincipalTest.java @@ -20,10 +20,11 @@ */ package org.apache.qpid.server.security.auth.sasl; -import java.security.Principal; -import javax.security.auth.Subject; import junit.framework.TestCase; +import javax.security.auth.Subject; +import java.security.Principal; + /** * Tests the UsernamePrincipal. * diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/signal/SignalHandlerTaskTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/signal/SignalHandlerTaskTest.java index 886cb080aa..23ee82eae6 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/signal/SignalHandlerTaskTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/signal/SignalHandlerTaskTest.java @@ -20,13 +20,14 @@ */ package org.apache.qpid.server.signal; +import org.apache.log4j.Logger; + +import org.apache.qpid.test.utils.QpidTestCase; + import java.lang.management.ManagementFactory; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -import org.apache.log4j.Logger; -import org.apache.qpid.test.utils.QpidTestCase; - public class SignalHandlerTaskTest extends QpidTestCase { private static final Logger LOGGER = Logger.getLogger(SignalHandlerTaskTest.class); diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/stats/StatisticsCounterTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/stats/StatisticsCounterTest.java index fbaa1342c9..147879f5e8 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/stats/StatisticsCounterTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/stats/StatisticsCounterTest.java @@ -106,7 +106,12 @@ public class StatisticsCounterTest extends TestCase Thread.sleep(1500); assertEquals(0.0, counter.getPeak()); counter.registerEvent(2000, start + 1500); - Thread.sleep(1000L); + + // make sure, that getPeak invocation occurs at "start + 2500" + // if test thread over-sleeps for 500+ mls + // the peak value can be incremented and test will fail + long sleep = start + 2500 - System.currentTimeMillis(); + Thread.sleep(sleep < 0 ? 0 : sleep); assertEquals(0.0, counter.getPeak()); counter.registerEvent(1000, start + 500); Thread.sleep(1500); diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/store/MessageStoreTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/store/MessageStoreTest.java index 90adaa1319..d49f0586ba 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/store/MessageStoreTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/store/MessageStoreTest.java @@ -20,12 +20,8 @@ */ package org.apache.qpid.server.store; -import java.io.File; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import org.apache.commons.configuration.PropertiesConfiguration; + import org.apache.qpid.AMQException; import org.apache.qpid.common.AMQPFilterTypes; import org.apache.qpid.framing.AMQShortString; @@ -58,6 +54,11 @@ import org.apache.qpid.server.util.InternalBrokerBaseCase; import org.apache.qpid.server.virtualhost.VirtualHost; import org.apache.qpid.util.FileUtils; +import java.io.File; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + /** * This tests the MessageStores by using the available interfaces. * @@ -70,26 +71,26 @@ public class MessageStoreTest extends InternalBrokerBaseCase public static final String SELECTOR_VALUE = "Test = 'MST'"; public static final String LVQ_KEY = "MST-LVQ-KEY"; - AMQShortString nonDurableExchangeName = new AMQShortString("MST-NonDurableDirectExchange"); - AMQShortString directExchangeName = new AMQShortString("MST-DirectExchange"); - AMQShortString topicExchangeName = new AMQShortString("MST-TopicExchange"); + private AMQShortString nonDurableExchangeName = new AMQShortString("MST-NonDurableDirectExchange"); + private AMQShortString directExchangeName = new AMQShortString("MST-DirectExchange"); + private AMQShortString topicExchangeName = new AMQShortString("MST-TopicExchange"); - AMQShortString durablePriorityTopicQueueName = new AMQShortString("MST-PriorityTopicQueue-Durable"); - AMQShortString durableTopicQueueName = new AMQShortString("MST-TopicQueue-Durable"); - AMQShortString priorityTopicQueueName = new AMQShortString("MST-PriorityTopicQueue"); - AMQShortString topicQueueName = new AMQShortString("MST-TopicQueue"); + private AMQShortString durablePriorityTopicQueueName = new AMQShortString("MST-PriorityTopicQueue-Durable"); + private AMQShortString durableTopicQueueName = new AMQShortString("MST-TopicQueue-Durable"); + private AMQShortString priorityTopicQueueName = new AMQShortString("MST-PriorityTopicQueue"); + private AMQShortString topicQueueName = new AMQShortString("MST-TopicQueue"); - AMQShortString durableExclusiveQueueName = new AMQShortString("MST-Queue-Durable-Exclusive"); - AMQShortString durablePriorityQueueName = new AMQShortString("MST-PriorityQueue-Durable"); - AMQShortString durableLastValueQueueName = new AMQShortString("MST-LastValueQueue-Durable"); - AMQShortString durableQueueName = new AMQShortString("MST-Queue-Durable"); - AMQShortString priorityQueueName = new AMQShortString("MST-PriorityQueue"); - AMQShortString queueName = new AMQShortString("MST-Queue"); + private AMQShortString durableExclusiveQueueName = new AMQShortString("MST-Queue-Durable-Exclusive"); + private AMQShortString durablePriorityQueueName = new AMQShortString("MST-PriorityQueue-Durable"); + private AMQShortString durableLastValueQueueName = new AMQShortString("MST-LastValueQueue-Durable"); + private AMQShortString durableQueueName = new AMQShortString("MST-Queue-Durable"); + private AMQShortString priorityQueueName = new AMQShortString("MST-PriorityQueue"); + private AMQShortString queueName = new AMQShortString("MST-Queue"); - AMQShortString directRouting = new AMQShortString("MST-direct"); - AMQShortString topicRouting = new AMQShortString("MST-topic"); + private AMQShortString directRouting = new AMQShortString("MST-direct"); + private AMQShortString topicRouting = new AMQShortString("MST-topic"); - AMQShortString queueOwner = new AMQShortString("MST"); + private AMQShortString queueOwner = new AMQShortString("MST"); protected PropertiesConfiguration _config; @@ -586,11 +587,7 @@ public class MessageStoreTest extends InternalBrokerBaseCase currentMessage.setExchange(exchange); - ContentHeaderBody headerBody = new ContentHeaderBody(); - headerBody.classId = BasicConsumeBodyImpl.CLASS_ID; - headerBody.bodySize = 0; - - headerBody.setProperties(properties); + ContentHeaderBody headerBody = new ContentHeaderBody(BasicConsumeBodyImpl.CLASS_ID,0,properties,0l); try { @@ -603,7 +600,7 @@ public class MessageStoreTest extends InternalBrokerBaseCase currentMessage.setExpiration(); - MessageMetaData mmd = currentMessage.headersReceived(); + MessageMetaData mmd = currentMessage.headersReceived(System.currentTimeMillis()); currentMessage.setStoredMessage(getVirtualHost().getMessageStore().addMessage(mmd)); currentMessage.getStoredMessage().flushToStore(); currentMessage.route(); diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/store/SkeletonMessageStore.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/store/SkeletonMessageStore.java index 44006df517..09d865cb05 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/store/SkeletonMessageStore.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/store/SkeletonMessageStore.java @@ -21,21 +21,14 @@ package org.apache.qpid.server.store; import org.apache.commons.configuration.Configuration; -import org.apache.qpid.AMQException; + import org.apache.qpid.AMQStoreException; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.framing.abstraction.ContentChunk; -import org.apache.qpid.server.message.EnqueableMessage; -import org.apache.qpid.server.message.MessageMetaData; -import org.apache.qpid.server.queue.AMQQueue; import org.apache.qpid.server.exchange.Exchange; -import org.apache.qpid.server.message.ServerMessage; import org.apache.qpid.server.logging.LogSubject; - -import java.util.List; -import java.util.concurrent.atomic.AtomicLong; -import java.nio.ByteBuffer; +import org.apache.qpid.server.message.EnqueableMessage; +import org.apache.qpid.server.queue.AMQQueue; /** * A message store that does nothing. Designed to be used in tests that do not want to use any message store @@ -153,6 +146,14 @@ public class SkeletonMessageStore implements MessageStore { } + + public void removeXid(long format, byte[] globalId, byte[] branchId) + { + } + + public void recordXid(long format, byte[] globalId, byte[] branchId, Record[] enqueues, Record[] dequeues) + { + } }; } diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/store/TestMemoryMessageStore.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/store/TestMemoryMessageStore.java index fa698f4cf8..8a261b3b86 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/store/TestMemoryMessageStore.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/store/TestMemoryMessageStore.java @@ -20,14 +20,8 @@ */ package org.apache.qpid.server.store; -import org.apache.qpid.server.message.MessageMetaData; -import org.apache.qpid.framing.abstraction.ContentChunk; - -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.List; import java.nio.ByteBuffer; +import java.util.concurrent.atomic.AtomicInteger; /** * Adds some extra methods to the memory message store for testing purposes. diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/store/TestableMemoryMessageStore.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/store/TestableMemoryMessageStore.java index 3804d0dc8e..104e06d29a 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/store/TestableMemoryMessageStore.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/store/TestableMemoryMessageStore.java @@ -20,22 +20,21 @@ */ package org.apache.qpid.server.store; -import java.nio.ByteBuffer; -import java.util.HashMap; -import java.util.concurrent.atomic.AtomicInteger; - import org.apache.qpid.AMQStoreException; import org.apache.qpid.server.message.EnqueableMessage; -import org.apache.qpid.server.message.ServerMessage; import org.apache.qpid.server.queue.AMQQueue; +import java.nio.ByteBuffer; +import java.util.HashMap; +import java.util.concurrent.atomic.AtomicInteger; + /** * Adds some extra methods to the memory message store for testing purposes. */ public class TestableMemoryMessageStore extends MemoryMessageStore { - MemoryMessageStore _mms = null; + private MemoryMessageStore _mms = null; private HashMap _messages = new HashMap(); private AtomicInteger _messageCount = new AtomicInteger(0); @@ -101,6 +100,14 @@ public class TestableMemoryMessageStore extends MemoryMessageStore public void abortTran() throws AMQStoreException { } + + public void removeXid(long format, byte[] globalId, byte[] branchId) + { + } + + public void recordXid(long format, byte[] globalId, byte[] branchId, Record[] enqueues, Record[] dequeues) + { + } } diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/subscription/MockSubscription.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/subscription/MockSubscription.java index 4a74596d02..f1eb2281e8 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/subscription/MockSubscription.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/subscription/MockSubscription.java @@ -21,12 +21,6 @@ package org.apache.qpid.server.subscription; * */ -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - import org.apache.qpid.AMQException; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.server.AMQChannel; @@ -35,6 +29,12 @@ import org.apache.qpid.server.queue.AMQQueue; import org.apache.qpid.server.queue.QueueEntry; import org.apache.qpid.server.queue.QueueEntry.SubscriptionAcquiredState; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + public class MockSubscription implements Subscription { @@ -55,6 +55,7 @@ public class MockSubscription implements Subscription private static final AtomicLong idGenerator = new AtomicLong(0); // Create a simple ID that increments for ever new Subscription private final long _subscriptionID = idGenerator.getAndIncrement(); + private boolean _isActive = true; public MockSubscription() { @@ -150,7 +151,7 @@ public class MockSubscription implements Subscription public boolean isActive() { - return true; + return _isActive ; } public void set(String key, Object value) @@ -270,4 +271,9 @@ public class MockSubscription implements Subscription { //TODO } + + public void setActive(final boolean isActive) + { + _isActive = isActive; + } } diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/subscription/QueueBrowserUsesNoAckTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/subscription/QueueBrowserUsesNoAckTest.java index b315a79b33..3272bd5447 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/subscription/QueueBrowserUsesNoAckTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/subscription/QueueBrowserUsesNoAckTest.java @@ -20,10 +20,10 @@ */ package org.apache.qpid.server.subscription; -import org.apache.qpid.server.util.InternalBrokerBaseCase; -import org.apache.qpid.server.protocol.InternalTestProtocolSession; -import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.AMQException; +import org.apache.qpid.framing.AMQShortString; +import org.apache.qpid.server.protocol.InternalTestProtocolSession; +import org.apache.qpid.server.util.InternalBrokerBaseCase; import java.util.List; diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/transport/ServerConnectionMBeanTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/transport/ServerConnectionMBeanTest.java index 78ba8c1645..dcb3692cf5 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/transport/ServerConnectionMBeanTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/transport/ServerConnectionMBeanTest.java @@ -20,15 +20,6 @@ */ package org.apache.qpid.server.transport; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.List; -import java.util.UUID; -import java.util.concurrent.atomic.AtomicLong; -import javax.management.JMException; -import javax.management.openmbean.CompositeData; -import javax.management.openmbean.TabularData; import org.apache.qpid.management.common.mbeans.ManagedConnection; import org.apache.qpid.server.configuration.MockConnectionConfig; import org.apache.qpid.server.registry.ApplicationRegistry; @@ -38,6 +29,16 @@ import org.apache.qpid.transport.Binary; import org.apache.qpid.transport.Connection; import org.apache.qpid.transport.Session; +import javax.management.JMException; +import javax.management.openmbean.CompositeData; +import javax.management.openmbean.TabularData; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicLong; + public class ServerConnectionMBeanTest extends InternalBrokerBaseCase { private ServerConnection _serverConnection; diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/txn/AutoCommitTransactionTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/txn/AutoCommitTransactionTest.java index 98484db264..cd3fe3c473 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/txn/AutoCommitTransactionTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/txn/AutoCommitTransactionTest.java @@ -20,10 +20,6 @@ */ package org.apache.qpid.server.txn; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - import org.apache.qpid.server.message.ServerMessage; import org.apache.qpid.server.queue.AMQQueue; import org.apache.qpid.server.queue.MockAMQQueue; @@ -33,6 +29,10 @@ import org.apache.qpid.server.store.MessageStore; import org.apache.qpid.server.txn.MockStoreTransaction.TransactionState; import org.apache.qpid.test.utils.QpidTestCase; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + /** * A unit test ensuring that AutoCommitTransaction creates a separate transaction for * each dequeue/enqueue operation that involves enlistable messages. Verifies diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/txn/LocalTransactionTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/txn/LocalTransactionTest.java index 484beb8fb4..5992829f37 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/txn/LocalTransactionTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/txn/LocalTransactionTest.java @@ -20,10 +20,6 @@ */ package org.apache.qpid.server.txn; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - import org.apache.qpid.server.message.ServerMessage; import org.apache.qpid.server.queue.AMQQueue; import org.apache.qpid.server.queue.MockAMQQueue; @@ -33,6 +29,10 @@ import org.apache.qpid.server.store.MessageStore; import org.apache.qpid.server.txn.MockStoreTransaction.TransactionState; import org.apache.qpid.test.utils.QpidTestCase; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + /** * A unit test ensuring that LocalTransactionTest creates a long-lived store transaction * that spans many dequeue/enqueue operations of enlistable messages. Verifies diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/txn/MockServerMessage.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/txn/MockServerMessage.java index 063023f5b3..1dc4619476 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/txn/MockServerMessage.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/txn/MockServerMessage.java @@ -20,15 +20,16 @@ */ package org.apache.qpid.server.txn; -import java.nio.ByteBuffer; - import org.apache.commons.lang.NotImplementedException; + import org.apache.qpid.server.configuration.SessionConfig; import org.apache.qpid.server.message.AMQMessageHeader; import org.apache.qpid.server.message.MessageReference; import org.apache.qpid.server.message.ServerMessage; import org.apache.qpid.server.store.StoredMessage; +import java.nio.ByteBuffer; + /** * Mock Server Message allowing its persistent flag to be controlled from test. */ diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/txn/MockStoreTransaction.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/txn/MockStoreTransaction.java index bf8fda307a..801549e561 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/txn/MockStoreTransaction.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/txn/MockStoreTransaction.java @@ -22,13 +22,18 @@ package org.apache.qpid.server.txn; import org.apache.commons.configuration.Configuration; import org.apache.commons.lang.NotImplementedException; + import org.apache.qpid.AMQStoreException; import org.apache.qpid.server.logging.LogSubject; import org.apache.qpid.server.message.EnqueableMessage; -import org.apache.qpid.server.message.ServerMessage; -import org.apache.qpid.server.store.*; +import org.apache.qpid.server.store.MessageStore; import org.apache.qpid.server.store.MessageStore.StoreFuture; import org.apache.qpid.server.store.MessageStore.Transaction; +import org.apache.qpid.server.store.MessageStoreRecoveryHandler; +import org.apache.qpid.server.store.StorableMessageMetaData; +import org.apache.qpid.server.store.StoredMessage; +import org.apache.qpid.server.store.TransactionLogRecoveryHandler; +import org.apache.qpid.server.store.TransactionLogResource; /** * Mock implementation of a (Store) Transaction allow its state to be observed. @@ -107,6 +112,14 @@ class MockStoreTransaction implements Transaction _state = TransactionState.ABORTED; } + public void removeXid(long format, byte[] globalId, byte[] branchId) + { + } + + public void recordXid(long format, byte[] globalId, byte[] branchId, Record[] enqueues, Record[] dequeues) + { + } + public static MessageStore createTestTransactionLog(final MockStoreTransaction storeTransaction) { return new MessageStore() diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/util/InternalBrokerBaseCase.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/util/InternalBrokerBaseCase.java index a97134a58d..9df0aec545 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/util/InternalBrokerBaseCase.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/util/InternalBrokerBaseCase.java @@ -21,6 +21,7 @@ package org.apache.qpid.server.util; import org.apache.commons.configuration.XMLConfiguration; + import org.apache.qpid.AMQException; import org.apache.qpid.common.AMQPFilterTypes; import org.apache.qpid.exchange.ExchangeDefaults; @@ -30,10 +31,10 @@ import org.apache.qpid.framing.ContentHeaderBody; import org.apache.qpid.framing.FieldTable; import org.apache.qpid.framing.abstraction.MessagePublishInfo; import org.apache.qpid.server.AMQChannel; -import org.apache.qpid.server.logging.SystemOutMessageLogger; -import org.apache.qpid.server.logging.actors.CurrentActor; import org.apache.qpid.server.configuration.ServerConfiguration; import org.apache.qpid.server.exchange.Exchange; +import org.apache.qpid.server.logging.SystemOutMessageLogger; +import org.apache.qpid.server.logging.actors.CurrentActor; import org.apache.qpid.server.logging.actors.TestLogActor; import org.apache.qpid.server.protocol.InternalTestProtocolSession; import org.apache.qpid.server.queue.AMQQueue; @@ -231,7 +232,7 @@ public class InternalBrokerBaseCase extends QpidTestCase //Set the body size ContentHeaderBody _headerBody = new ContentHeaderBody(); - _headerBody.bodySize = 0; + _headerBody.setBodySize(0); //Set Minimum properties BasicContentHeaderProperties properties = new BasicContentHeaderProperties(); diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/util/LoggingProxyTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/util/LoggingProxyTest.java deleted file mode 100644 index c7db51016e..0000000000 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/util/LoggingProxyTest.java +++ /dev/null @@ -1,88 +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.util; - -import java.util.Arrays; -import java.util.Collection; -import java.util.List; - -import junit.framework.TestCase; - -public class LoggingProxyTest extends TestCase -{ - static interface IFoo { - void foo(); - void foo(int i, Collection c); - String bar(); - String bar(String s, List l); - } - - static class Foo implements IFoo { - public void foo() - { - } - - public void foo(int i, Collection c) - { - } - - public String bar() - { - return null; - } - - public String bar(String s, List l) - { - return "ha"; - } - } - - public void testSimple() { - LoggingProxy proxy = new LoggingProxy(new Foo(), 20); - IFoo foo = (IFoo)proxy.getProxy(IFoo.class); - foo.foo(); - assertEquals(2, proxy.getBufferSize()); - assertTrue(proxy.getBuffer().get(0).toString().matches(".*: foo\\(\\) entered$")); - assertTrue(proxy.getBuffer().get(1).toString().matches(".*: foo\\(\\) returned$")); - - foo.foo(3, Arrays.asList(0, 1, 2)); - assertEquals(4, proxy.getBufferSize()); - assertTrue(proxy.getBuffer().get(2).toString().matches(".*: foo\\(\\[3, \\[0, 1, 2\\]\\]\\) entered$")); - assertTrue(proxy.getBuffer().get(3).toString().matches(".*: foo\\(\\) returned$")); - - foo.bar(); - assertEquals(6, proxy.getBufferSize()); - assertTrue(proxy.getBuffer().get(4).toString().matches(".*: bar\\(\\) entered$")); - assertTrue(proxy.getBuffer().get(5).toString().matches(".*: bar\\(\\) returned null$")); - - foo.bar("hello", Arrays.asList(1, 2, 3)); - assertEquals(8, proxy.getBufferSize()); - assertTrue(proxy.getBuffer().get(6).toString().matches(".*: bar\\(\\[hello, \\[1, 2, 3\\]\\]\\) entered$")); - assertTrue(proxy.getBuffer().get(7).toString().matches(".*: bar\\(\\) returned ha$")); - - proxy.dump(); - } - - public static junit.framework.Test suite() - { - return new junit.framework.TestSuite(LoggingProxyTest.class); - } -} diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/util/TestApplicationRegistry.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/util/TestApplicationRegistry.java index 3c6857e8a9..7aa5ed23fe 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/util/TestApplicationRegistry.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/util/TestApplicationRegistry.java @@ -20,20 +20,21 @@ */ package org.apache.qpid.server.util; -import java.util.Properties; - import org.apache.commons.configuration.ConfigurationException; + import org.apache.qpid.server.configuration.ServerConfiguration; +import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin; import org.apache.qpid.server.logging.NullRootMessageLogger; import org.apache.qpid.server.logging.actors.BrokerActor; import org.apache.qpid.server.logging.actors.CurrentActor; import org.apache.qpid.server.logging.actors.GenericActor; -import org.apache.qpid.server.configuration.plugins.ConfigurationPlugin; import org.apache.qpid.server.registry.ApplicationRegistry; import org.apache.qpid.server.security.auth.database.PropertiesPrincipalDatabase; import org.apache.qpid.server.security.auth.manager.AuthenticationManager; import org.apache.qpid.server.security.auth.manager.PrincipalDatabaseAuthenticationManager; +import java.util.Properties; + public class TestApplicationRegistry extends ApplicationRegistry { diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/HouseKeepingTaskTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/HouseKeepingTaskTest.java index 98bf381712..0794154e47 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/HouseKeepingTaskTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/HouseKeepingTaskTest.java @@ -20,14 +20,14 @@ */ package org.apache.qpid.server.virtualhost; -import java.util.concurrent.CountDownLatch; - import org.apache.qpid.server.logging.LogActor; import org.apache.qpid.server.logging.NullRootMessageLogger; import org.apache.qpid.server.logging.actors.CurrentActor; import org.apache.qpid.server.logging.actors.TestLogActor; import org.apache.qpid.test.utils.QpidTestCase; +import java.util.concurrent.CountDownLatch; + public class HouseKeepingTaskTest extends QpidTestCase { /** diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/MockVirtualHost.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/MockVirtualHost.java index b2cdff89ee..54c44d8cc4 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/MockVirtualHost.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/MockVirtualHost.java @@ -20,9 +20,7 @@ */ package org.apache.qpid.server.virtualhost; -import java.util.Map; -import java.util.UUID; - +import java.util.concurrent.ScheduledFuture; import org.apache.qpid.server.binding.BindingFactory; import org.apache.qpid.server.configuration.BrokerConfig; import org.apache.qpid.server.configuration.ConfigStore; @@ -43,6 +41,10 @@ import org.apache.qpid.server.stats.StatisticsCounter; import org.apache.qpid.server.store.DurableConfigurationStore; import org.apache.qpid.server.store.MessageStore; import org.apache.qpid.server.protocol.v1_0.LinkRegistry; +import org.apache.qpid.server.txn.DtxRegistry; + +import java.util.Map; +import java.util.UUID; public class MockVirtualHost implements VirtualHost @@ -96,6 +98,11 @@ public class MockVirtualHost implements VirtualHost return null; } + public DtxRegistry getDtxRegistry() + { + return null; + } + public VirtualHostConfiguration getConfiguration() { return null; @@ -172,6 +179,11 @@ public class MockVirtualHost implements VirtualHost } + public ScheduledFuture scheduleTask(long delay, Runnable timeoutTask) + { + return null; + } + public void scheduleHouseKeepingTask(long period, HouseKeepingTask task) { diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/VirtualHostImplTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/VirtualHostImplTest.java index c87e5a1648..df7b4da426 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/VirtualHostImplTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/VirtualHostImplTest.java @@ -20,13 +20,9 @@ */ package org.apache.qpid.server.virtualhost; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; - import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.XMLConfiguration; + import org.apache.qpid.server.configuration.ServerConfiguration; import org.apache.qpid.server.exchange.Exchange; import org.apache.qpid.server.queue.AMQQueue; @@ -35,6 +31,11 @@ import org.apache.qpid.server.store.TestableMemoryMessageStore; import org.apache.qpid.server.util.TestApplicationRegistry; import org.apache.qpid.test.utils.QpidTestCase; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; + public class VirtualHostImplTest extends QpidTestCase { private ServerConfiguration _configuration; diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetectionConfigurationTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetectionConfigurationTest.java index cc11d68e07..e2375c579b 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetectionConfigurationTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetectionConfigurationTest.java @@ -23,6 +23,7 @@ package org.apache.qpid.server.virtualhost.plugins; import org.apache.commons.configuration.CompositeConfiguration; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.XMLConfiguration; + import org.apache.qpid.server.configuration.plugins.SlowConsumerDetectionConfiguration; import org.apache.qpid.server.util.InternalBrokerBaseCase; diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetectionPolicyConfigurationTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetectionPolicyConfigurationTest.java index efb898e365..ea07632873 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetectionPolicyConfigurationTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetectionPolicyConfigurationTest.java @@ -23,6 +23,7 @@ package org.apache.qpid.server.virtualhost.plugins; import org.apache.commons.configuration.CompositeConfiguration; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.XMLConfiguration; + import org.apache.qpid.server.configuration.plugins.SlowConsumerDetectionPolicyConfiguration; import org.apache.qpid.server.util.InternalBrokerBaseCase; diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetectionQueueConfigurationTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetectionQueueConfigurationTest.java index be86037dd8..96e524acf2 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetectionQueueConfigurationTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetectionQueueConfigurationTest.java @@ -21,6 +21,7 @@ package org.apache.qpid.server.virtualhost.plugins; import org.apache.commons.configuration.CompositeConfiguration; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.XMLConfiguration; + import org.apache.qpid.server.configuration.plugins.SlowConsumerDetectionQueueConfiguration; import org.apache.qpid.server.util.InternalBrokerBaseCase; diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/policies/TopicDeletePolicyConfigurationTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/policies/TopicDeletePolicyConfigurationTest.java index 3d3cc810df..f034d05c37 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/policies/TopicDeletePolicyConfigurationTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/policies/TopicDeletePolicyConfigurationTest.java @@ -23,6 +23,7 @@ package org.apache.qpid.server.virtualhost.plugins.policies; import org.apache.commons.configuration.CompositeConfiguration; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.XMLConfiguration; + import org.apache.qpid.server.util.InternalBrokerBaseCase; /** diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/policies/TopicDeletePolicyTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/policies/TopicDeletePolicyTest.java index a2e83add05..fdd163b323 100644 --- a/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/policies/TopicDeletePolicyTest.java +++ b/qpid/java/broker/src/test/java/org/apache/qpid/server/virtualhost/plugins/policies/TopicDeletePolicyTest.java @@ -22,6 +22,7 @@ package org.apache.qpid.server.virtualhost.plugins.policies; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.XMLConfiguration; + import org.apache.qpid.AMQException; import org.apache.qpid.server.AMQChannel; import org.apache.qpid.server.binding.Binding; @@ -38,10 +39,10 @@ import org.apache.qpid.server.virtualhost.VirtualHost; public class TopicDeletePolicyTest extends InternalBrokerBaseCase { - TopicDeletePolicyConfiguration _config; + private TopicDeletePolicyConfiguration _config; - VirtualHost _defaultVhost; - InternalTestProtocolSession _connection; + private VirtualHost _defaultVhost; + private InternalTestProtocolSession _connection; public void setUp() throws Exception { diff --git a/qpid/java/broker/src/test/java/org/apache/qpid/tools/security/PasswdTest.java b/qpid/java/broker/src/test/java/org/apache/qpid/tools/security/PasswdTest.java new file mode 100644 index 0000000000..b2a7234c8a --- /dev/null +++ b/qpid/java/broker/src/test/java/org/apache/qpid/tools/security/PasswdTest.java @@ -0,0 +1,38 @@ +/* + * 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.tools.security; + +import junit.framework.TestCase; + +public class PasswdTest extends TestCase +{ + public void testUserGuestAndPasswordGuest() throws Exception + { + Passwd passwd = new Passwd(); + String output = passwd.getOutput("guest", "guest"); + assertEquals("guest:CE4DQ6BIb/BVMN9scFyLtA==", output); + } + + public void testUser1AndPasswordFoo() throws Exception + { + Passwd passwd = new Passwd(); + String output = passwd.getOutput("user1", "foo"); + assertEquals("user1:rL0Y20zC+Fzt72VPzMSk2A==", output); + } +} diff --git a/qpid/java/broker/src/velocity/java/org/apache/qpid/server/logging/GenerateLogMessages.java b/qpid/java/broker/src/velocity/java/org/apache/qpid/server/logging/GenerateLogMessages.java index a39799a6b6..a10d3b6a77 100644 --- a/qpid/java/broker/src/velocity/java/org/apache/qpid/server/logging/GenerateLogMessages.java +++ b/qpid/java/broker/src/velocity/java/org/apache/qpid/server/logging/GenerateLogMessages.java @@ -68,8 +68,7 @@ public class GenerateLogMessages } catch (InvalidTypeException e) { - // This occurs when a type other than 'number' appears in the - // paramater config {0, number...} + // This occurs when a type other than 'number' appears in the paramater config {0, number...}. System.err.println(e.getMessage()); System.exit(-1); } @@ -365,9 +364,9 @@ public class GenerateLogMessages // Taking an example of: // 'Text {n,type,format} [option] text {m} [option with param{p}] more' // This would give us: - // 0 - Text {n,type,format} - // 1 - option] text {m} - // 2 - option with param{p}] more + // 0 - Text {n,type,format}. + // 1 - option] text {m}. + // 2 - option with param{p}] more. // Create the parameter list for this item List> options = new LinkedList>(); @@ -442,17 +441,20 @@ public class GenerateLogMessages String[] parametersString = logMessage.split("\\{"); // Taking an example of 'Text {n[,type]} text {m} more text {p}' // This would give us: - // 0 - Text - // 1 - n[,type]} text - // 2 - m} more text - // 3 - p} + // 0 - Text. + // 1 - n[,type]} text. + // 2 - m} more text. + // 3 - p}. // Create the parameter list for this item List> parameters = new LinkedList>(); - // Check that we have some parameters to process - // Skip 0 as that will not be the first entry - // Text {n[,type]} text {m} more text {p} + /* + Check that we have some parameters to process + Skip 0 as that will not be the first entry + Text {n[,type]} text {m} more text {p}. + */ + if (parametersString.length > 1) { for (int index = 1; index < parametersString.length; index++) @@ -461,8 +463,11 @@ public class GenerateLogMessages // for easy retrieval in the macro template HashMap parameter = new HashMap(); - // Check for any properties of the parameter : - // e.g. {0} vs {0,number} vs {0,number,xxxx} + /* + Check for any properties of the parameter : + e.g. {0} vs {0,number} vs {0,number,xxxx}. + */ + int typeIndex = parametersString[index].indexOf(","); // The parameter type diff --git a/qpid/java/broker/src/velocity/templates/org/apache/qpid/server/logging/messages/LogMessages.vm b/qpid/java/broker/src/velocity/templates/org/apache/qpid/server/logging/messages/LogMessages.vm index fd847fd513..02bf155c44 100644 --- a/qpid/java/broker/src/velocity/templates/org/apache/qpid/server/logging/messages/LogMessages.vm +++ b/qpid/java/broker/src/velocity/templates/org/apache/qpid/server/logging/messages/LogMessages.vm @@ -43,8 +43,8 @@ import java.util.ResourceBundle; */ public class ${type.name}Messages { - static ResourceBundle _messages; - static Locale _currentLocale; + private static ResourceBundle _messages; + private static Locale _currentLocale; public static final String ${type.name.toUpperCase()}_LOG_HIERARCHY = DEFAULT_LOG_HIERARCHY_PREFIX + "${type.name.toLowerCase()}"; #foreach( $message in ${type.list} ) @@ -146,7 +146,7 @@ public class ${type.name}Messages ## append it to the log. #foreach($option in ${message.options}) - // Add Option : ${option.value} + // Add Option : ${option.value}. end = parts[${velocityCount}].indexOf(']'); if (${option.name}) { @@ -197,4 +197,8 @@ public class ${type.name}Messages #end + private ${type.name}Messages() + { + } + } diff --git a/qpid/java/broker/src/xsl/qmf.xsl b/qpid/java/broker/src/xsl/qmf.xsl index 1e98c97466..c45d1e419e 100644 --- a/qpid/java/broker/src/xsl/qmf.xsl +++ b/qpid/java/broker/src/xsl/qmf.xsl @@ -794,9 +794,14 @@ public class extends QMFPackage OBJECTREFERENCE STR8 STR16 +UINT8 UINT16 UINT32 UINT64 +INT8 +INT16 +INT32 +INT64 UUID DELTATIME UINT32 @@ -813,9 +818,14 @@ public class extends QMFPackage Object String String + Integer Integer Long Long + Integer + Integer + Long + Long UUID Long Long @@ -831,9 +841,14 @@ public class extends QMFPackage writeBin128( .getId() ) writeStr8( ) writeStr16( ) + writeUint8( ) writeUint16( ) writeUint32( ) writeUint64( ) + writeInt8( ) + writeInt16( ) + writeInt32( ) + writeInt64( ) writeUuid( ) writeUint64( ) writeUint32( ) @@ -849,9 +864,14 @@ public class extends QMFPackage readBin128() readStr8() readStr16() + readUint8() readUint16() readUint32() readUint64() + readInt8() + readInt16() + readInt32() + readInt64() readUuid() readUint64() readUint32() diff --git a/qpid/java/client/README.txt b/qpid/java/client/README.txt index b9cde71db3..a8c7da32c5 100644 --- a/qpid/java/client/README.txt +++ b/qpid/java/client/README.txt @@ -47,5 +47,3 @@ Run 'ant build' in the parent directory from where this file is stored, ie: This will build the various Java modules, leaving binary .jar files output in: /qpid/java/build/lib -Taking the above the 'distribution directory', consult the README.txt file at: -/qpid/java/client/example/src/main/java diff --git a/qpid/java/client/build.xml b/qpid/java/client/build.xml index d52de8dca6..5a72d67b68 100644 --- a/qpid/java/client/build.xml +++ b/qpid/java/client/build.xml @@ -32,14 +32,6 @@ - - - - - - diff --git a/qpid/java/client/example/src/main/java/README.txt b/qpid/java/client/example/src/main/java/README.txt deleted file mode 100644 index 757054e492..0000000000 --- a/qpid/java/client/example/src/main/java/README.txt +++ /dev/null @@ -1,33 +0,0 @@ -In order to use the runSample script, you are required to set two environment -variables, QPID_HOME and QPID_SAMPLE. If not the default values will be used. - -QPID_HOME ---------- -This is the directory that contains the QPID distribution. If you are running the Qpid -Java broker on the same machine as the examples, you have already set QPID_HOME to this -directory. - -default: /usr/share/java/ - -QPID_SAMPLE ------------ - -This is the examples directory, which is the parent directory of the -'java' directory in which you find 'runSample.sh' - -(Ex:- $QPID_SRC_HOME/java/client/example/src/main) - -default: $PWD - -Note: you must have write privileges to this directory in order to run -the examples. - - -Running the Examples -=========================== - -To run these programs, do the following: - - 1. Make sure that a Qpid broker is running. - 2. In the java directory, use runSample.sh to run the program: - $ ./runSample.sh \ No newline at end of file diff --git a/qpid/java/client/example/src/main/java/org/apache/qpid/example/Drain.java b/qpid/java/client/example/src/main/java/org/apache/qpid/example/Drain.java index b43031ad23..28e1d5a87e 100644 --- a/qpid/java/client/example/src/main/java/org/apache/qpid/example/Drain.java +++ b/qpid/java/client/example/src/main/java/org/apache/qpid/example/Drain.java @@ -27,8 +27,6 @@ import javax.jms.MessageConsumer; import javax.jms.Session; import org.apache.qpid.client.AMQAnyDestination; -import org.apache.qpid.client.AMQConnection; -import org.slf4j.Logger; public class Drain extends OptionParser { @@ -50,13 +48,13 @@ public class Drain extends OptionParser static { - optDefs.add(BROKER); - optDefs.add(HELP); - optDefs.add(TIMEOUT); - optDefs.add(FOREVER); - optDefs.add(COUNT); - optDefs.add(CON_OPTIONS); - optDefs.add(BROKER_OPTIONS); + addOption(BROKER); + addOption(HELP); + addOption(TIMEOUT); + addOption(FOREVER); + addOption(COUNT); + addOption(CON_OPTIONS); + addOption(BROKER_OPTIONS); } public Drain(String[] args, String usage, String desc) throws Exception @@ -66,7 +64,7 @@ public class Drain extends OptionParser Connection con = createConnection(); con.start(); Session ssn = con.createSession(false,Session.AUTO_ACKNOWLEDGE); - Destination dest = new AMQAnyDestination(address); + Destination dest = new AMQAnyDestination(getAddress()); MessageConsumer consumer = ssn.createConsumer(dest); Message msg; diff --git a/qpid/java/client/example/src/main/java/org/apache/qpid/example/OptionParser.java b/qpid/java/client/example/src/main/java/org/apache/qpid/example/OptionParser.java index f4e17c5c4c..6aa12f07fa 100644 --- a/qpid/java/client/example/src/main/java/org/apache/qpid/example/OptionParser.java +++ b/qpid/java/client/example/src/main/java/org/apache/qpid/example/OptionParser.java @@ -68,12 +68,12 @@ public class OptionParser String.class); - protected Map optMap = new HashMap(); - protected static final List